我创建了一个链接到saveButton的IBAction,当我在IBAction中调用所有核心数据方法时,它可以在以下代码中正常工作:
- (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,在获取时显示为null。它没有返回错误,但我在谷歌搜索一整天后都不知道。有人能指出我的代码有什么问题吗?
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
答案 0 :(得分:1)
Person不需要保存功能。
person.firstName = firstNameTextField.text
相当于
[self setValue:self.firstName forKey:@“firstName”];
你需要的是这样的:
(IBAction为)saveButtonTap:(ID)发送方{
person.firstName = firstNameTextField.text;
person.lastName = lastNameTextField.text;
NSError * error = nil;
if(![context save:& error])
NSLog(@"Can't save transaction - %@ || %@ ", error, [error localizedDescription]);
}
但是,我不确定这是否是问题的原因。试试吧,让我知道。