I’m still new to NSMangedObjects and I’m having trouble replacing objects at a certain index.
for (NSString *file in filelist){
NSManagedObject *fileEntity = [NSEntityDescription insertNewObjectForEntityForName:@"File" inManagedObjectContext:[self managedObjectContext]];
[fileEntity setValue:file forKey:@"filename"];
NSImage *audioImage = [NSImage imageNamed:@"tag_white.png"];
[fileEntity setValue:audioImage forKey:@"taggedImage"];
[markedAudioFiles addObject:audioImage];
}
As you can see I can easily insert into the managed object just fine. It displays the files on a table and everything. However, I want to change some values at a certain index for the @"taggedImage" key.
So I tried something like this:
NSEntityDescription *fileEntity = [NSEntityDescription entityForName:@"File" inManagedObjectContext:[self managedObjectContext]];
NSImage *audioImage = [NSImage imageNamed:@"tag_green.png"];
[fileEntity replaceValueAtIndex:index inPropertyWithKey:@"taggedImage" withValue:audioImage];
The error I get is:
[ valueForUndefinedKey:]: this class
is not key value coding-compliant for the key taggedImage.
I even tried replacing the fileEntity declaration above with
NSManagedObject *fileEntity = [NSEntityDescription insertNewObjectForEntityForName:@"File" inManagedObjectContext:[self managedObjectContext]];
but since it’s not a new object I figured that’s wrong.
In your second block of code
fileEntityis just a description of an object, it isn’t an actualNSManagedObjectso it won’t have the keytaggedImages.However, that’s not the real reason you’re code won’t work. THere’s a bigger problem in what I think you’re trying to do isn’t the way to do it!
If you’re trying to update the
taggedImageproperty of theFileobject at index n, that’s not the way to do it. Your first problem is how are the File objects ordered in CoreData – is it by name, is it by created on date, is it by random? You don’t know so asking for the item at n doesn’t make any sense yet!You need to query your data store and get the items in a specific order (See
NSFetchRequestand the Core Data tutorial from Apple.Once you have your file objects out of core data in the order you want then you can just get the item at index n, update it’s taggedImage and then save it.
PS However, this will get very inefficient with lots of items in core data if you have to get them all each time you only want to update one 🙂