My first question is how do you plan to identify when two objects use the same image? Is there a property on the image that you can save and query to determine if an already installed image exists? And how expensive is it, computationally? If this takes a long time, you can end up optimizing for storage and performance impact.
However, if you have a way to do this efficiently, you can create an ImageBlob object to do what you describe. An entity that uses ImageBlob must have an ImageBlob or imageBlobs with ImageBlob . ImageBlob should have feedback with the name, for example, users .
In your code, when you want to reuse ImageBlob , it is as simple as doing something like this:
NSManagedObject *blob = // get the image blob NSManagedObject *user = // get the user [user setValue:blob forKey:@"imageBlob"]; // do this if it uses a single image [[user mutableSetValueForKey:@"imageBlobs"] addObject:blob]; // do this if it uses multiple images
Another consideration that you want to think about is what you need to do with blobs that are no longer needed. Presumably you want to delete any images that are not in use. To do this, you can register an application delegate or a subclass of NSPersistentDocument (depending on whether your application is document-based or not) to notify NSManagedObjectContextObjectsDidChangeNotification . Whenever the context of a managed entity changes, you can delete any unnecessary images, for example:
- (void)managedObjectContextObjectsDidSave:(NSNotification *)notification { NSManagedObjectContext *managedObjectContext = [notification object]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:[NSEntity entityWithName:@"ImageBlob" inManagedObjectContext:managedObjectContext]]; [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@" users.@count == 0"]; NSArray *unusedBlobs = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
source share