在NSManagedObject中使用IF语句

时间:2015-03-24 01:29:21

标签: ios objective-c nsmanagedobject

我正在尝试使用if语句来识别条目是否已保存到我的核心数据文件中。在这种情况下,我想在文本字段中显示用户名,以便他们可以编辑它然后重新保存。相反,它只是将每个条目都视为新条目,即使它已被创建。此外,如果我尝试显示已保存对象的文本,即使在viewDidLoad方法中,也不会显示任何内容。

帮助将不胜感激,谢谢。

- (IBAction)savePressed:(id)sender {

    NSManagedObjectContext *context = [self managedObjectContext];

    if(playerObject) {

        //update exsisting
        [playerObject setValue:txtFieldName.text forKey:@"name"];


    }
    else {
        //create new player

        NSManagedObject *newPlayer = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:context];
        [newPlayer setValue:txtFieldName.text forKey:@"name"];

    }


    //save
    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Save Failed! %@ %@", error, [error localizedDescription]);
    }


    [self dismissViewControllerAnimated:YES completion:nil];

}

1 个答案:

答案 0 :(得分:0)

认为您忘记将新创建的播放器分配给iVar playerObject:

NSManagedObject *newPlayer = nil;

if(playerObject) {
    //update exsisting
    [playerObject setValue:txtFieldName.text forKey:@"name"];
} else {
    //create new player

    newPlayer = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:context];
    [newPlayer setValue:txtFieldName.text forKey:@"name"];

}

if (![context save:&error]) {
        NSLog(@"Save Failed! %@ %@", error, [error localizedDescription]);
} else {
    if (newPlayer) {
        playerObject = newPlayer;
    }
}