2013-11-23 22 views
0

我創造了我鏈接到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 
+1

在[self.person保存]中刪除自己; – Rugmangathan

回答

1

沒有必要保存功能的人。

person.firstName = firstNameTextField.text

相當於

[自的setValue:self.firstName forKey:@ 「名字」];

你需要什麼,僅僅是這樣的:

  • (IBAction爲)saveButtonTap:(ID)發送{

    person.firstName = firstNameTextField.text;

    person.lastName = lastNameTextField.text;

    NSError * error = nil;

    如果(![上下文保存:&錯誤])

    NSLog(@"Can't save transaction - %@ || %@ ", error, [error localizedDescription]); 
    

    }

但是,我不知道這是否是問題的原因。嘗試一下,讓我知道。

+0

感謝Harris,它幫助我調試並理解如何繼承NSManagedObject類。但我仍然不知道背後的邏輯是如何工作的。當我爲類屬性賦值時,然後將setValue調用到它的屬性中,是不是很像firstName = firstName和lastName = lastName? (如果我錯了,請糾正我),而是返回'null'。 –

+0

我在想同樣的事,那就是爲什麼,不知道這是否會導致問題。但是,我們不知道內部。使用屬性的設置值更有可能調用setValue:如果這個調用是異步完成的,很難預測何時會設置實際值(爲什麼會這樣做,只有蘋果知道)。 –