Copy what cannot be NSCopied

Sometimes you need to deep-copy an object in Objective-C.  Normally you just go newObject = [oldObject copy].  But what if oldObject does not support NSCopying (typified by the error “copyWithZone: unrecognized selector”)?

Well.. if your object supports NSCoding, then you can simply serialize it, and deserialize it!  Saves you having to monkey-patch the copyWithZone method (though may be a tiny bit less efficient at runtime).

How can do you perform this voodoo magic?  just one line of code…

newObject = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:oldObject]];

NB. (for iPhone programmers) ‘newObject’ is autoreleased, so make sure you retain it somewhere!

There you go.  This hack was brought to you by the people behind GPS Log for iPhone (please check it out, it’s free to try!).

Where do I use this?  Well I have some UITableViewCell objects that I defined in an XIB file, but I need lots of copies (this is a pretty common use-case, which the SDK does not handle very well at all).  Instead of sticking the object in it’s own XIB file, and loading it from the XIB each time (as is one workaround), I use the trick above :)  And it’s more more efficient (object is copied in memory, rather than loaded from flash-storage).

In fact, many UI elements don’t support copying, but they do support serializing, so this can be pretty useful. For UI elements, you may need to add this monkey-patch to get UIImage to play nice.

*name

*e-mail

web site

leave a comment