2014-03-28 58 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]; 
    } 
}