我創造了我鏈接到saveButton一個IBAction爲,當我打電話的所有核心數據方法的IBAction爲內正常工作在下面的代碼:擷取的managedObject返回null
- (IBAction)saveButtonTap:(id)sender{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *object = [NSEntityDescription insertNewObjectFor:@"Person" inManagedContext:context];
[self setValue:firstNameTextField.text forKey:@"firstName"];
[self setValue:lastNameTextField.text forKey:@"lastName"];
NSError *error = nil;
if (![context save:&error])
NSLog(@"Can't save transaction - %@ || %@ ", error, [error localizedDescription]);
}
當我分開的核心數據保存方法如下所示,保存的firstName和lastName在獲取時顯示爲空。它沒有返回錯誤,但我一整天都不知道Google搜索結果。有人能指出我的代碼有什麼問題嗎?
Person.h + Person.m
@interface Person : NSManagedObject
@property(strong) NSString *firstName;
@property(strong) NSString *lastName;
- (void)save;
@end
@implementation Person
@synthesize firstName;
@synthesize lastName;
- (void)save{
[self setValue:self.firstName forKey:@"firstName"];
[self setValue:self.lastName forKey:@"lastName"];
}
@end
mainViewController.h + mainViewController.m
@interface mainViewController : UIViewController
@property(strong) ManagedObjectContext *context;
@property(strong) Person *person;
- (IBAction)saveButtonTap:(id)sender;
@end
@implementation mainViewController
@synthesize context;
@synthesize person;
- (void)viewDidLoad{
// ... some view did Load rituals
if(context == nil){
context = [self managedObjectContext]; // Assume this method calls for managed object context from shared application.
}
if(person == nil){
person = [NSEntityDescription insertNewObjectFor:@"Person" inManagedContext:context];
}
}
- (IBAction)saveButtonTap:(id)sender{
person.firstName = firstNameTextField.text;
person.lastName = lastNameTextField.text;
[self.person save];
NSError *error = nil;
if (![context save:&error])
NSLog(@"Can't save transaction - %@ || %@ ", error, [error localizedDescription]);
}
@end
在[self.person保存]中刪除自己; – Rugmangathan