2012-11-18 40 views
0

我想爲我的CoreData項目做一個保存按鈕,通常我沒有問題。但是這次我沒有看到它保存到SQL文件(在FireFox中使用SQLite),也不能將數據拉回到UITableView中。ios Coredata - 我的savebutton不工作

沒有錯誤或警告。有人可以幫我在我陰霾的星期天下午(新西蘭時間)頭)?

- (IBAction)saveDataAction:(id)sender 
{ 
//Instantiating the Entity with a pointer and giving it a mission. 
NSString *details = @"Details"; 
NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:details inManagedObjectContext:[self managedObjectContext]]; 

int yearOfBirth = [_yearTxtField.text intValue]; //Converting the value from a String into an int 
NSNumber *year = [NSNumber numberWithInt:yearOfBirth]; //Converting the int into a NSNumber 

//Setting each textField value to an attribute in the Entity. 
[newObject setValue:_nameTxtField.text forKey:@"name"]; 
[newObject setValue:_streetTxtField.text forKey:@"streetName"]; 
[newObject setValue:_cityTxtField.text forKey:@"cityName"]; 
[newObject setValue:year forKey:@"yearOfBirth"]; 

//This log just shows what has been added to the database. 
//NSLog(@"Details Save:\n\n Name: %@\n StreetName: %@\n CityName: %@\n Year of birth: %@", details.name, details.streetName, details.cityName, details.yearOfBirth); 
} 
+0

您需要保存上下文的背景下,添加的對象之後。試試我的代碼 –

回答

0
- (IBAction)saveDataAction:(id)sender 
{ 
    //Instantiating the Entity with a pointer and giving it a mission. 
    NSString *details = @"Details"; 
    NSManagedObjectContext *context = [self managedObjectContext]; 
    NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:details inManagedObjectContext:context]; 

    int yearOfBirth = [_yearTxtField.text intValue]; //Converting the value from a String into an int 
    NSNumber *year = [NSNumber numberWithInt:yearOfBirth]; //Converting the int into a NSNumber 

    //Setting each textField value to an attribute in the Entity. 
    [newObject setValue:_nameTxtField.text forKey:@"name"]; 
    [newObject setValue:_streetTxtField.text forKey:@"streetName"]; 
    [newObject setValue:_cityTxtField.text forKey:@"cityName"]; 
    [newObject setValue:year forKey:@"yearOfBirth"]; 

    NSError *error; 
    if (![context save:&error]) { 
     NSLog(@"Whoops couldn't save new object"); 
    } 
    //This log just shows what has been added to the database. 
    //NSLog(@"Details Save:\n\n Name: %@\n StreetName: %@\n CityName: %@\n Year of birth: %@", details.name, details.streetName, details.cityName, details.yearOfBirth); 
} 
+0

Yip做了它 - 小錯誤:-) –

+0

完成刪除或更新或插入後,您始終需要保存上下文。不要忘記:-) @JeffKranenburg。 –