2012-03-25 4 views
4

私は辞書の配列であるplistファイルを持っています。各辞書には一連の文字列が含まれます。各辞書は有名人を表します。アプリケーションのplistでコアデータを先に投入する

最初に起動したアプリケーションのこのplistの内容をCore Dataに入力してから、コアデータに何かデータの有無をチェックしたい場合は、データがある場合はロードしますそれ以外の場合は、plistファイルから初期データを再度ロードします。

plistからコアデータを取り込むことは可能ですが、私は実行可能なソリューションを提案していますか?それとも良い方法がありますか?

ジャック

答えて

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]; 
} 
+0

非常に良い、ありがとう。 –

+0

'NSDictionary * node = [dict objectForKey:key]'ではありませんか?さもなければ、NSDictionaryのセレクタとして認識されていない 'key'についての警告を受け取ると思います。 – sirvine

+0

@sirvineもちろん! – NeverBe

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); 
    }; 
} 
+0

1つの質問; NSManagedObject * newTopic ...をNSManagedObjectサブクラス名に置き換える必要がありますか?もう1つ、8行目のexecuteFetchRequestを実行して、トピック配列を取得して、その値が0かどうかをテストできますか?あなたが最初のテストのためにテストするなら、それはゼロでなければなりません、そうですか?私はこのgithubの要点を思いついたところで、サーバーとコードImの結果データセットを投稿しました:https://gist.github.com/quique123/5126202 – marciokoko

+0

非常に長い遅延のため申し訳ありません!私はStackOverflowで受信トレイがあることに気付かなかった。はい - その要求の唯一の目的はテストすることです。ほとんどのデータはそこにあるので、システムはユーザーに渡してコンテンツを配信します。 – Tim

関連する問題