预先填充核心数据,仅在应用程序首次启动时使用plist

时间:2012-03-25 16:57:44

标签: iphone objective-c ios core-data property-list

我有一个plist文件,它是一个字典数组。每个字典包含一组字符串。每个词典代表一个名人。

我想要做的是在应用程序首次启动时使用此plist的内容填充Core Data,之后我想以某种方式检查核心数据是否存在我的数据,如果有数据,请加载它从那里,否则再次从plist文件加载初始数据。

我知道可以从plist中填充核心数据,但是我建议一个可行的解决方案吗?或者有更好的方法吗?

杰克

2 个答案:

答案 0 :(得分:8)

我的示例代码

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if (![defaults objectForKey:@"dataImported"]) {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"dict" ofType:@"plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
    for (NSString *key in [dict allKeys]) {
        NSDictionary *node = [dict objectForKey:key];

        MyClass *newObj = .....
    }

   [defaults setObject:@"OK" forKey:@"dataImported"];
   [defaults synchronize];
}

答案 1 :(得分:0)

这是做同样的事情,但有一个稍微复杂的pList,它包含一个字典数组,表示要存储的“主题”的数据。它仍然有一些调试日志记录。希望它对某人有用。

NSManagedObjectContext *context = self.managedObjectContext;
NSError *error;

NSFetchRequest *topicRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *topicEntityDescription = [NSEntityDescription entityForName:@"Topic" inManagedObjectContext:context];
[topicRequest setEntity:topicEntityDescription];
NSManagedObject *newTopic = nil;
NSArray *topics = [context executeFetchRequest:topicRequest error:&error];
if (error) NSLog(@"Error encountered in executing topic fetch request: %@", error);

if ([topics count] == 0)  // No topics in database so we proceed to populate the database
{
    NSString *topicsPath = [[NSBundle mainBundle] pathForResource:@"topicsData" ofType:@"plist"];
    NSArray *topicsDataArray = [[NSArray alloc] initWithContentsOfFile:topicsPath];
    int numberOfTopics = [topicsDataArray count];

    for (int i = 0; i<numberOfTopics; i++)
    {
        NSDictionary *topicDataDictionary = [topicsDataArray objectAtIndex:i];
        newTopic = [NSEntityDescription insertNewObjectForEntityForName:@"Topic" inManagedObjectContext:context];
        [newTopic setValuesForKeysWithDictionary:topicDataDictionary];
        [context save:&error];
        if (error) NSLog(@"Error encountered in saving topic entity, %d, %@, Hint: check that the structure of the pList matches Core Data: %@",i, newTopic, error);
    };
}