2012-02-17 79 views
0

我是一個從頭開始學習新手和學習核心數據。 我已經設置了coredatamodel,然後創建了NSManagedObject類。然後在應用程序委託中,我嘗試插入一些測試數據。但是,它沒有正常工作。只有最後一個數據被插入。我應該放置使用核心數據添加多個測試數據

[self saveContext];

在每個物體之間?在「applicationWillTerminate」方法中,saveContext方法被調用,因此最後的項目被保存。 (是否正確?)

NSManagedObjectContext *context = [self managedObjectContext]; 

Vocabulary *vocabulary = [NSEntityDescription 
            insertNewObjectForEntityForName:@"Vocabulary" 
            inManagedObjectContext:context]; 

vocabulary.word = @"iPhone"; 
vocabulary.definition = @"better than Android"; 
vocabulary.level = @"beginner"; 

vocabulary.word = @"iPhone3gs"; 
vocabulary.definition = @"better than 3"; 
vocabulary.level = @"intermediate"; 

vocabulary.word = @"iPhone4"; 
vocabulary.definition = @"better than 3gs"; 
vocabulary.level = @"advanced"; 

vocabulary.word = @"iPhone4s"; 
vocabulary.definition = @"better than 4"; 

vocabulary.word = @"iPhone4s"; 
vocabulary.definition = @"64 is better than 32"; 
vocabulary.level = @"advanced"; 

回答

0

您需要爲插入的每個詞彙表對象插入一個新實體。所以這樣做:

Vocabulary *vocabulary = nil; 
NSManagedObjectContext *context = [self managedObjectContext]; 

vocabulary = [NSEntityDescription insertNewObjectForEntityForName:@"Vocabulary" inManagedObjectContext:context]; 
vocabulary.word = @"iPhone"; 
vocabulary.definition = @"better than Android"; 
vocabulary.level = @"beginner"; 

vocabulary = [NSEntityDescription insertNewObjectForEntityForName:@"Vocabulary" inManagedObjectContext:context]; 
vocabulary.word = @"iPhone3gs"; 
vocabulary.definition = @"better than 3"; 
vocabulary.level = @"intermediate"; 

vocabulary = [NSEntityDescription insertNewObjectForEntityForName:@"Vocabulary" inManagedObjectContext:context]; 
vocabulary.word = @"iPhone4"; 
vocabulary.definition = @"better than 3gs"; 
vocabulary.level = @"advanced"; 

vocabulary = [NSEntityDescription insertNewObjectForEntityForName:@"Vocabulary" inManagedObjectContext:context]; 
vocabulary.word = @"iPhone4s"; 
vocabulary.definition = @"better than 4"; 

vocabulary = [NSEntityDescription insertNewObjectForEntityForName:@"Vocabulary" inManagedObjectContext:context]; 
vocabulary.word = @"iPhone4s"; 
vocabulary.definition = @"64 is better than 32"; 
vocabulary.level = @"advanced"; 
+0

謝謝蒂姆。有用! – Vector 2012-02-17 04:10:11