2012-05-07 37 views
0

我有一種情況,我應該通過UIViewController將對象插入實體。我設計了我的數據庫模型(實體和屬性)。我通過UIViewController添加實體。我應該在appDelegate.m的didFinishLaunchingwithOptions方法中添加什麼?通過視圖控制器向實體添加數據

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // Override point for customization after application launch 
    return YES; 
} 

而對於TUTViewController(我自己的觀點控制器 - UIViewController)我用下面的代碼用於插入對象。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; 
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; 
    NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; 

    NSString *stripped1 = [response stringByReplacingOccurrencesOfString:@"\r" withString:@""]; 
    NSMutableArray *rows = [NSMutableArray arrayWithArray:[stripped1 componentsSeparatedByString:@"\n"]]; 
    NSMutableArray *contentArray = [NSMutableArray arrayWithCapacity:[rows count]]; 
    NSMutableArray *contentArray1 = [NSMutableArray arrayWithCapacity:[rows count]]; 

    NSArray *components; 
    NSLog(@"count:%d",[rows count]); 

    for (int i=0;i<[rows count]; i++) { 

     if(i == 0 || [[rows objectAtIndex:i] isEqualToString:@""]){ 
      continue; 
     } 

     components = [[rows objectAtIndex:i] componentsSeparatedByString:@","]; 
     id x = [components objectAtIndex:0] ; 
     id y = [components objectAtIndex:1]; 
     id z = [components objectAtIndex:2]; 

     [contentArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x,@"X",y,@"Y", nil]]; 
     [contentArray1 addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:x,@"X",z,@"Y", nil]]; 

     [newManagedObject setValue:[x] forKey:@"timeStamp"]; 
     [newManagedObject setValue:[y] forKey:@"beat"]; 
     [newManagedObject setValue:[z] forKey:@"rate"]; 

     // Save the context. 
     NSError *error = nil; 
     if (![context save:&error]) { 

      NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
      abort(); 

      NSLog(@"Contents of Uterus Contraction: %@",contentArray); 
      NSLog(@"Contents of Heart Beat: %@",contentArray1); 
     }  
    } 
} 

有什麼我失蹤了嗎?我結束了錯誤:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'FetalData''

回答

0

您是否設置了核心數據堆棧或UIManagedDocument對象?

如果您沒有設置託管對象模型,這可能是問題所在。這意味着你可能沒有加載定義了FetalData實體的託管對象模型。有關更多信息,請參見insertnewobjectforentityforname

我真的建議創建一個空的項目,讓Xcode爲你創建核心數據。通過這種方式,你可以看到代碼是如何工作的。

一些注意

爲什麼你使用NSFetchResultsController

在方法結尾處調用save調用。以這種方式避免多次往返磁盤。

如果你想開始使用核心數據,我建議你core-data-on-ios-5-tutorial-getting-started

希望它有幫助。

相關問題