5

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

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

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

杰克

4

2 回答 2

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];
}
于 2012-03-25T17:14:39.143 回答
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);
    };
}
于 2013-01-17T09:25:04.803 回答