views:

11

answers:

1

Hi All

I need to edit a row of data in an Entity that has a relationship with my main Entity from my fetchedResultsController, in this case "theUser" being an instance of my User entity.

I basically need to edit one of the CannedMessage rows that already exist and save it. I can access the "Messages" fine as you see below, but am unsure once I have found the CannedMessage I want as to how I save it back into the managedObjectContext for "theUser"

Any advice?

NSArray *msgs = [theUser.Messages allObjects];

NSPredicate *activeMatch = [NSPredicate predicateWithFormat:@"defaultMessage == 1"];
NSArray *matched = [msgs filteredArrayUsingPredicate:activeMatch];

CannedMessage *msgToEdit;

for(CannedMessage *msg in matched) {
    msgToEdit = msg;
}
A: 

Your trouble is that your thinking in SQL terms instead of Core Data's object oriented terms. The data you are looking for is not in an SQL row but in the attribute of a managed object. In this case (I assume) you are looking for an attribute of a CannedMessage instance.

The matched array will contain either managed objects initialized with the CannedMessage entity or an instance of a dedicated NSManagedObject subclass (if you setup one which it looks like you did.)

Lets say the attribute is named theMsg. To access the attribute in the generic managed objects:

for(CannedMessage *msg in matched) {
    msgToEdit = [msg valueForKey:@"theMsg"];
}

... to access a custom class:

for(CannedMessage *msg in matched) {
    msgToEdit = msg.theMsg;
}

It's really important when learning Core Data to simply forget everything you know about SQL. Nothing about SQL truly translates into Core Data. Core Data is not an object-oriented wrapped around SQL. Entities are not tables, relationships are not link tables or joins, attributes are not columns and values are not rows. Instead, Core Data creates objects just like you would if you manually wrote a custom class to model a real world object, event or condition. Core Data uses SQL almost as an after thought as one of its many persistence options.

In my experience, the more you know about SQL, the harder it is to shift gears to Core Data and other object graph APIs. You want to translate the new stuff to what you have already mastered. It is natural but resist the urge.

TechZen