2012-03-25 3 views
4

사전의 배열 인 plist 파일이 있습니다. 각 사전에는 문자열 세트가 들어 있습니다. 각 사전은 유명인을 나타냅니다.코어 데이터를 응용 프로그램의 plist로 미리 채우기 시작

코어 데이터에 애플리케이션 시작시이 plist의 내용을 채우고 싶습니다. 그런 다음 코어 데이터에 내 데이터의 존재 여부를 확인하고 싶습니다. 데이터가 있으면로드하십시오. 거기에서, 그렇지 않으면 다시 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에 대한 인식기가 아닌 '키'에 대한 경고 메시지가 표시됩니다. – sirvine

+0

@ 솔잎! – 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

한 가지 질문; NSManagedObject * newTopic ... NSManagedObject 하위 클래스 이름을 대체해야합니까? 한 가지 더, 당신은 8 행의 executeFetchRequest를 실행하여 주제 배열을 얻습니다. 0이면 테스트 할 수 있습니까? 왜냐하면 첫 번째 테스트를하면 0이 될 것입니다. 맞습니까? 나는 서버와 코드 Im의 결과 데이터 세트를 게시 한이 github 요점을 생각해 냈습니다. https://gist.github.com/quique123/5126202 – marciokoko

+0

죄송합니다. 매우 오래 지연됩니다! 나는 StackOverflow에받은 편지함이 있다는 것을 알지 못했다. 예 - 요청의 유일한 목적은 테스트하는 것입니다. 대부분의 데이터는 시스템이 지나가도록하여 사용자에게 컨텐츠를 전달합니다. – Tim

관련 문제