载入一个NSDictionary数组到Core Data的简单方法



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

我有一个字典数组,其中包括包含键值对的字典,包括key: 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];
        }
    }
}

如果你的字典只包含你的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];
    }
}

稍微干净一点:

-(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];
    }
}

最新更新