Home > OS >  Adding value to NSObject key- Expression is not assignable
Adding value to NSObject key- Expression is not assignable

Time:04-28

I’m trying to add a value I get back from an API call to an object in objective C. I get an error in Xcode saying “Expression is not assignable” and don’t understand why. In my carObj I have an object called warrantyPlan with a nil value and I’m trying to set the value for warrantyPlan. What am I doing wrong in this method?

NSArray *carUUIDs = [carData valueForKeyPath:@"uuid"];
                        NSString *ownerUUID = ownerRecord[@"uuid"];
                        if (ownerID) {
                            NSManagedObjectContext *context = [DataCenter viewContext];
                            NSObject *carObj = [context objectsForEntityName:[CarObject entityName] matchingUUIDs:carUUIDs];
                            
                            for (id carID in carUUIDs){
                                [WarrantyPlansService getWarrantyPlansForCarWithCarID:carID ownerID:ownerUUID completion:^(NSArray* response, NSError* error){
                                    //attach the response to the carData
                                    NSLog(@"%@", [carObj valueForKeyPath:@"warrantyPlans"]);
                                    [carObj valueForKeyPath:@"warrantyPlans"] = response;
                                }];
                            }

CodePudding user response:

[carObj valueForKeyPath:@"warrantyPlans"] is an expression that has a value like literally 42 is an expression that has a value. It's not an expression like foo that is a variable that has a value of 42 and can be changed by using it on the left hand side of an equals sign.

To change it you want:

[carObj setValue:response forKeyPath:@"warrantyPlans"]

These two are called the generic getter valueForKey: and the generic setter setValue:forKey: in the KeyValueCoding guide: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/index.html

  • Related