1

我在核心数据中有一个名为“类别”的实体,它有 3 个属性。

  1. parent_id
  2. 类别ID
  3. 分类名称

现在在根字典下的 CategoriesFile.plist 中,我创建了 3 个名为

  1. parent_id
  2. 类别ID
  3. 分类名称

我已经在这些数组中填充了适当的数据。

现在我编写了以下代码来插入数据

   NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsPath = [paths objectAtIndex:0];
        NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"CategoriesFile.plist"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
        {
            // if not in documents, get property list from main bundle
            plistPath = [[NSBundle mainBundle] pathForResource:@"CategoriesFile" ofType:@"plist"];
        }

        // read property list into memory as an NSData object
        NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
        NSString *errorDesc = nil;
        NSPropertyListFormat format;

        // convert static property list into dictionary object
        NSDictionary *thisGardenDictionary = [[NSDictionary alloc] init];
        NSDictionary *plistDictionary = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
        if (!plistDictionary)
        {
            NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
        }

        [plistDictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id key, id object, BOOL *stop) {
            NSManagedObject *manObj = [NSEntityDescription insertNewObjectForEntityForName:@"Categories" inManagedObjectContext:context];

            [manObj setValue:[thisGardenDictionary objectForKey:@"category_id"]  forKey:@"category_id"];
        [manObj setValue:[thisGardenDictionary objectForKey:@"parent_id"] forKey:@"parent_id"];
        [manObj setValue:[thisGardenDictionary objectForKey:@"category_name"] forKey:@"category_name"];


             }];
 NSError *error;
    if(![context save:&error])
    {
        NSLog(@"Whoops, couldn't save %@",[error localizedDescription]);
    }

但我得到空白的结果。

有人可以说我错过了什么吗?

4

2 回答 2

0

应该这样做(我相信您已验证 plist 已正确读取):

NSDictionary *allArrays = [NSDictionary dictionaryWithContentsOfFile:plistPath];
for (int i = 0; i < [[allArrays objectForKey:@"parent_id"] count]; i++) {
   NSManagedObject *object = [NSEntityDescription 
    insertNewObjectForEntityForName:@"Categories" 
             inManagedObjectContext:context];
    for (NSString *s in @[@"parent_id", @"category_id", @"category_name"]) {
      [object setValue:[[allArrays objectForKey:s] objectAtIndex:i] forKey:s];
    }
}
// save

但是,让我指出,这是组织数据的一种非常尴尬的方式。更好的是一系列字典。在您的设置中,如果所有数组的元素数量不同,结果将是灾难性的。

于 2012-12-10T21:27:16.170 回答
0

NSManagedObject 设置你的属性

[manObj setName:@"Name"];

等等......然后保存上下文以将值存储在CoreData db中。

if (![context save:&error]) {
   NSLog(@"Unresolved error : %@", [error userInfo]);
}
于 2012-12-06T08:08:00.577 回答