将NSDictionary数组加载到Core Data中的简便方法

时间:2014-03-28 23:54:03

标签: ios objective-c core-data nsdictionary

我需要在我的核心数据模型中导入外部文件作为初始数据。

我有一个字典数组,其中包含包含键值对的字典,包括键:firstName John,lastName Jones等。

我想出了以下内容来加载数据,但我想知道是否有更简单优雅的方式来做这件事,我不知道。我搜索了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];
        }
    }
}

2 个答案:

答案 0 :(得分: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];
    }
}

答案 1 :(得分: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];
    }
}