Search code examples
objective-cmemory-managementmemory-efficient

Creating memory efficient objects in Objective-C


Suppose I have a Contact object with a name and photo only

@interface Contact: NSObject
{
    NSString *name;
    UIImage *photo;
}
@property (copy) NSString name;
@property (copy) UIImage photo;

suppose further that I live in a place where I have 1000 people called Sam and they're all clones so their photo look exactly the same and I decided to cheat and use the same photo for all of them.

Is Objective C smart enough that when a copy of the name and photo is taken it would recognise it has the same value and can be handled by one object and allocate just one NSString and one UIImage for all the Sams?

What is the correct way to handle this? Clearly I do need to make the them copy properties to handle non Sam cases and in case I get passed mutable strings and images.


Solution

  • UIImage doesn't conform to the NSCopying protocol, so the question is fairly moot. You need to change that copy on the photo property to a retain. This is perfectly fine for you since UIImage isn't mutable anyway (and has no mutable subclasses), so there's no need to copy it.

    As for the name, calling -copy on immutable objects (that support copying) tends to just retain the object instead of copying it. Calling it on the mutable variant of these objects (e.g. NSMutableString) will produce an immutable copy (which will itself respond to subsequent -copy requests by retaining). Note, however, that calling -copy on a mutable object multiple times will produce distinct immutable copies.