2017-05-26 86 views
0

下面是我的更新方法无法更新核心数据对象正确

-(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呢?

+0

你要什么给医生名称更改为?您在代码中唯一的值是您用于搜索记录的值 – Paulw11

回答

0

你需要有一个名称,它比一个已经存在的不同。现在您重新使用现有名称,并将doctorName设置为相同的值。

比方说,你调用此方法与“简·史密斯”的doctorName说法。当以下行运行时,您将只提取医生名称已经是“Jane Smith”的现有记录:

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

然后您执行以下操作。此时doctorName仍然是“简·史密斯”,并在firstResultdoctorName“简·史密斯”。你正在做的分配与已经存在相同的值:

firstResult.doctorName = doctorName; 

您的代码不会有不同医生姓名的任何地方。您正在更新该值,但您将其更新为已具有的值。

如果要更改名称,你需要有一个不同的名称来使用。如何做到这一点取决于你的应用程序的工作方式。也许你会为这个名为newDoctorName的方法添加一个参数,其中包含新名称。然后你会改变线之上阅读

firstResult.doctorName = newDoctorName; 

或者,也许你会改变你的谓语用其他的东西比doctorName。我不知道是什么 - 这又取决于你的应用程序的工作方式。