Update record using Core Data in iOS
I can't seem to find an example of how to update an existing row of data using Core Data on iOS. In te开发者_开发百科rms of SQL, I'm looking to do something along the lines of: UPDATE device SET attr1='blah', attr2='blah' WHERE deviceid='1';
I know I can do something like this: [device setValue:@"blah" forKey:@"attr1"];
However, how can I do that only WHERE the deviceid='1'?
Any help is appreciated.
With Core Data, you never execute SQL queries directly... you update the database simply by updating the value of your object, and then saving the managedObjectContext.
In your example, device is a specific instance of an object... [device setValue:@"blah" forKey:@"attr1"];
will only update that 1 device object, so you don't need any where clause.
If you need to retrieve the correct device object from the database, then you need to use a NSFetchRequest. I recommend looking through the Core Data Programming Guide to get an understanding of how Core Data works. If you are asking about SQL statements and WHERE clauses, it seems you have an incorrect view of what Core Data is.
Use the lastObject
method for safety reasons. If executeFetchRequest:error:
returns nil, your program will crash:
NSManagedObject *device = [fetchedObjects lastObject];
精彩评论