2014-03-28 21 views
1

我需要导入一个外部文件作为我的核心数据模型中的初始数据。简单的方法来加载一个NSDictionary数组到核心数据

我有字典的阵列,其包括包含密钥值对,包括诸如键字典:名字约翰,姓氏琼斯等

我想出了下述加载数据,但我想知道是否有一些更简单,更优雅的做法,我不知道。我搜索了关于NSDictionary和NSArray的参考资料,并且我没有找到似乎适合的东西。

//my attempt to load an array of dictionaries into my core data file 
-(void)loadUpNamesFromImportedFile 
{ 
if (!self.context) { 
    self.context = self.document.managedObjectContext; 
} 
ImportClientListFromFile *file = [[ImportClientListFromFile alloc]init]; 

self.clientListDictionary = [file fetchClientNamesFromFile]; 

self.clientNames = self.clientListDictionary; 

// enumerate the dictionaries, in the array of dictionaries which are from an imported file 
for (NSDictionary *attributeValue in self.clientNames) { 
    ClientInfo *info = [NSEntityDescription insertNewObjectForEntityForName:@"ClientInfo" inManagedObjectContext:self.context]; 

    //create an array which identifies attribute names to be used as keys to pull information from the dictionary 
    NSArray *keys = @[@"clientID",@"firstName",@"lastName",@"gender",@"phone",@"middleName",@"fullName"]; 

    //enumerate the keys array, and assign the value from the dictionary to each new object in the database 
    for (NSString *key in keys) { 
    [info setValue:[attributeValue valueForKey:key] forKeyPath:key]; 
     } 
    } 
} 
+1

为什么不将NsArray存储为可变形? – Jonathan

回答

0

如果你的字典里只包含对你的ClientInfo客户端属性名对象,你可以删除键数组要创建,只是使用的字典allKeys键。

// enumerate the dictionaries, in the array of dictionaries which are from an imported file 
for (NSDictionary *attributeValue in self.clientNames) { 
    ClientInfo *info = [NSEntityDescription insertNewObjectForEntityForName:@"ClientInfo" inManagedObjectContext:self.context]; 

    //enumerate the keys array, and assign the value from the dictionary to each new object in the database 
    for (NSString *key in [attributeValue allKeys]) { 
     [info setValue:[attributeValue valueForKey:key] forKeyPath:key]; 
    } 
} 
0

稍微干净:

-(void)loadUpNamesFromImportedFile { 
    if (!self.context) { 
     self.context = self.document.managedObjectContext; 
    } 
    ImportClientListFromFile *file = [[ImportClientListFromFile alloc] init]; 

    self.clientListDictionary = [file fetchClientNamesFromFile]; 

    self.clientNames = self.clientListDictionary; 

    // enumerate the dictionaries, in the array of dictionaries which are from an imported file 
    for (NSDictionary *attributeValue in self.clientNames) { 
     ClientInfo *info = [NSEntityDescription insertNewObjectForEntityForName:@"ClientInfo" inManagedObjectContext:self.context]; 
     [info setValuesForKeysWithDictionary:attributeValue]; 
    } 
}