核心数据初始化

时间:2014-06-20 21:32:22

标签: ios objective-c xcode core-data

我是coredata的新手,所以我有一个非常基本的问题 我有提供者实体,在viewDidLoad的视图控制器中我实现了这个方法:

-(NSDictionary *) allProviders {
    Providers *orangeFR = [NSEntityDescription insertNewObjectForEntityForName:@"Providers" inManagedObjectContext:self.managedObjectContext];
    orangeFR.name = [NSString stringWithFormat:@"Orange"];
    orangeFR.adress = [NSString stringWithFormat:@"Champ De Mars"];
    Providers *sfrFR = [NSEntityDescription insertNewObjectForEntityForName:@"Providers" inManagedObjectContext:self.managedObjectContext];
    sfrFR.name = [NSString stringWithFormat:@"SFR"];
    sfrFR.adress = [NSString stringWithFormat:@"SFR Adress"];
    NSArray *FRProviders = @[orangeFR, sfrFR];

    Providers *ATT = [NSEntityDescription insertNewObjectForEntityForName:@"Providers" inManagedObjectContext:self.managedObjectContext];
    BeelineRU.name = [NSString stringWithFormat:@"ATT"];
    BeelineRU.adress = [NSString stringWithFormat:@"ATT adress"];
    Providers *Verizon = [NSEntityDescription insertNewObjectForEntityForName:@"Providers" inManagedObjectContext:self.managedObjectContext];
    MTSRU.name = [NSString stringWithFormat:@"Verizon"];
    MTSRU.adress = [NSString stringWithFormat:@"Verizon Adress"];
    NSArray *USProviders = @[ATT, Verizon];


    _allProviders = @{@"France": FRProviders, @"USA":USProviders};
    return _allProviders;
}

所以一切正常,但在第二次启动应用程序时,我需要检查是否已经填充了我的Provider实体。怎么做,所以我可以在两种情况下得到我的_allProviders?

2 个答案:

答案 0 :(得分:0)

创建NSMutableDictionary

NSMutableDictionary *providersByCountry = [NSMutableDictionary dictionary]

获取所有实体:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"Providers" inManagedObjectContext:self.managedObjectContext];

NSArray *providers = [self.managedObjectContext executeFetchRequest:request error:NULL];

将您的提供者插入字典中(我假设您的country实体上有Providers属性...它有吗?):

for (Providers *provider in providers) {
    NSArray *providersForThisCountry = [providersByCountry[provider.country]
    if (!providersForThisCountry) {
        providersForThisCountry = [NSArray array];
    }

    providersForThisCountry = [providersForThisCountry arrayByAddingObject:provider];

    providersByCountry[provider.country] = providersForThisCountry;
}

最后,制作NSMutableDictionary的不可变副本,并将其返回:

return providersByCountry.copy;

由于这可能是一个相当慢的操作,您可能希望将结果缓存在私有@property中 - 但是每当修改提供者列表时,您都需要以某种方式清除缓存。

答案 1 :(得分:0)

NSArray* allProviders = [managedObjectContext executeFetchRequest:[[NSFetchRequest alloc] initWithEntityName:@"Providers"] error:nil];