【问题标题】:Storing in CoreData from Array of Dictionary objects从 Dictionary 对象数组中存储 CoreData
【发布时间】:2014-03-18 23:28:32
【问题描述】:

我有一个字典对象数组friendsArray,看起来像这样:

(
        {
        name = "james p";
        phone = 345345345;
    },
        {
        name = "sam b";
        phone = 345345345;
    },
        {
        name = "aaron s";
        phone = 346346456;
    }
)

现在我像这样将它存储到 coredata 中

 NSMutableDictionary *friends = [[NSMutableDictionary alloc] init];

   for (int count = 0; count <[friendsArray count]; count++) {
    NSError *error;
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"FriendContacts" inManagedObjectContext:context];
    NSManagedObject *friendsObject  = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];

    NSFetchRequest *request         = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];

    friends = [friendsArray objectAtIndex:count];
    [friendsObject setValue:[friends objectForKey:@"name"] forKey:@"name"];
    [friendsObject setValue:[friends objectForKey:@"phone"] forKey:@"phone"];
    [context save:&error];

 }

这是 SQL 浏览器的截图

它正在存储数据但复制了这个字典,我不知道为什么。

【问题讨论】:

  • 您不止一次运行该代码吗?尝试清除所有数据 - 重置模拟器,然后运行一次。
  • 我试过了 :) 它确实一直在重复。我知道我做错了什么,只是不知道是什么。
  • 添加一个日志,你因为某种原因运行了两次。
  • 是的,我只是不知道发生了什么

标签: ios core-data dictionary nsarray


【解决方案1】:

试试下面的 - 它有点干净:)

观察日志语句输出了多少次,检查输出的对象。

 NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"FriendContacts" inManagedObjectContext:context];
 for (NSDictionary *friend in friendsArray) {

    NSManagedObject *friendsObject  = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];

    [friendsObject setValue:[friend objectForKey:@"name"] forKey:@"name"];
    [friendsObject setValue:[friend objectForKey:@"phone"] forKey:@"phone"];

    NSLog(@"Created new friends object: %@", friendsObject);

    if ([context hasChanges]) {
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Problem saving changes: %@", error);
        }
    }
 }

编辑:

在循环结束后保存可能会更好(如果您有一个大数据集),只需将 if 语句移到循环之外。

【讨论】:

  • 天哪,我两次调用了相同的方法。多么愚蠢。很抱歉打扰你们.. 是的,我之前使用过快速枚举,但后来我切换到传统的 for 循环来检查我做错了什么哈哈..谢谢:)
  • @user3049559 始终如一。不过需要注意的是,如果您有很多对象,最好在 after 循环之后保存。我已经添加了一个关于这个的编辑。
猜你喜欢
  • 2023-03-06
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多