无法正确更新核心数据对象

时间:2017-05-26 08:59:46

标签: ios objective-c core-data

以下是我的更新方法

-(void)updateData:(NSString *)doctorName hospitalName:(NSString *)hospitalName emailAdd:(NSString *)emailAdd phoneNum:(NSString *)phoneNum mobileNum:(NSString *)mobileNum
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"DoctorInfo" inManagedObjectContext:delegate.persistentContainer.viewContext];

    NSFetchRequest *request = [NSFetchRequest new];
    [request setEntity:entityDesc];

    NSString *query = doctorName;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(doctorName = %@)", query];
    [request setPredicate:predicate];

    NSError *error;
    NSAsynchronousFetchResult *storeResult = [delegate.persistentContainer.viewContext executeRequest:request error:&error];
    NSArray *result = storeResult.finalResult;

    DoctorInfo *firstResult = [result firstObject];
    firstResult.doctorName = doctorName;
    firstResult.hospitalName = hospitalName;
    firstResult.emailAdd = emailAdd;
    firstResult.phoneNumber = phoneNum;
    firstResult.mobileNumber = mobileNum;

    if (![delegate.persistentContainer.viewContext save:&error]) {
        NSLog(@"Couldn't edit: %@", error);
    }
}

我可以更新除doctorName之外的所有变量。我想这可能是由于这行代码:

NSString *query = doctorName;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(doctorName = %@)", query];
    [request setPredicate:predicate];

我应该如何修改此方法以便我也可以更新doctorName?

1 个答案:

答案 0 :(得分:0)

您需要的名称与已存在的名称不同。现在,您正在重新使用现有名称,将doctorName设置为与其相同的值。

假设您使用“Jane Smith”的doctorName参数调用此方法。当以下行运行时,您将仅获取医生名称已经是“Jane Smith”的现有记录:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(doctorName = %@)", query];
[request setPredicate:predicate];

然后执行以下操作。此时doctorName仍然是“Jane Smith”,而doctorName上的firstResult 也是“Jane Smith”。你使用与已经存在的值相同的值进行赋值:

firstResult.doctorName = doctorName;

您的代码在任何地方都没有不同的医生姓名。您正在更新值,排序,但您将其更新为已有的值。

如果要更改名称,则需要使用其他名称。如何执行此操作取决于您的应用程序的工作方式。也许你会为这个名为newDoctorName的方法添加一个参数,其中包含新名称。然后你要改变上面的行来阅读

firstResult.doctorName = newDoctorName;

或许您可以将谓词更改为使用doctorName之外的其他内容。我不知道是什么 - 再次,这取决于你的应用程序是如何工作的。