2013-01-04 52 views
0

試圖更新一些核心數據。數據實際上是更新「某處」,但它不保存/更新數據庫。核心數據更新問題

- (IBAction)Update:(id)sender { 


    NSEntityDescription *entityDesc = 
    [NSEntityDescription entityForName:@"Preferences" 
       inManagedObjectContext:context]; 

    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    [request setEntity:entityDesc]; 


    NSError *error; 
    NSArray *objects = [context executeFetchRequest:request 
               error:&error]; 

    if ([objects count] == 0) { 
     // No update, didnt find any entries. 

    } else { 

     for (NSManagedObject *obj in objects) {   

      [obj setValue:_salesPrice.text forKey:@"value"]; 
      if(![context save:&error]){ 
       NSLog(@"Saving changes failed: %@", error); 
      } 

     } 

    } 
    //[context save:&error]; 
} 

我試過[context save:&error];在評論區域,但仍然沒有保存。保存時我也沒有錯誤。

回答

0

您只使用1 NSManagedObjectContext?你的命名習慣並不理想。通常你會命名實體偏好,因爲它的一個對象。嘗試下面的代碼。

CoreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
NSManagedObjectContext *context = [appDelegate managedObjectContext]; 
// This is for completion. Usually you should not get the context from the App Delegate. 
// Its better to pass it from the App Delegate to 
// the initial view controller via a property (dependency injection). 

NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([Preferences class])]; 
    NSError *error = nil; 
    NSArray *preferences = [context executeFetchRequest:req error:&error]; 

// Check error 

if ([preferences count] == 0) { 
    // No update, didnt find any entries. 
} else { 
    for (Preferences *preference in preferences) {   
     [preference setValue:_salesPrice.text forKey:@"value"]; 
    } 
} 
[context save:&error]; 
// Check error 
+0

沒有,同樣的問題,運行,但犯規保存到數據庫:( – llBuckshotll

+0

凡上下文中聲明你設置斷點檢查上下文和_salesPrice.text – Andy

+0

這就是它的價值在它被宣佈?: - (void)viewDidLoad。錯誤的教程/例子?一旦添加到更新功能它工作:) – llBuckshotll