2017-05-26 33 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。我不知道是什麼 - 這又取決於你的應用程序的工作方式。