objective-ciosmemory-managementcopywithzone

Why don’t iOS classes adopt copyWithZone protocol to encourage active mem mgt?


Recently turning to iOS after having worked with Cocoa, I was startled to get a SIGABRT with the following error: “-[UIDeviceRGBColor copyWithZone:]: unrecognized selector sent to instance…” I had called “copy” on a UIColor.

I looked at the class references and, zounds, UIColor does not adopt any protocols, in contrast to NSColor.

Now, this is not a big deal. I was just attempting to be more efficient by taking active ownership of a color instance so as to discard it immediately after use. But I thought the purpose behind Apple’s omitting a garbage collector in iOS was to encourage developers to do exactly what I was doing, to keep a lean memory profile on the memory-starved, battery-challenged portable devices.

Any ideas on Apple’s rationale, or is there some error in my assumptions?


Solution

  • I don't understand why you think implementing the NSCopying protocol would "encourage active memory management".

    Since UIColor is immutable (it implements no methods that change its internal state), there is no point making a copy. Just retain it if you want to keep it around, and release it when you're done. There is no need for anything else.

    If you really wanted, you could add copying in a category:

    @implementation UIColor (Copying) <NSCopying>
    
    - (id)copyWithZone:(NSZone *)zone
    {
        return [self retain];
    }
    
    @end
    

    But obviously that doesn't actually give you any new functionality. Apparently Apple didn't think it was worth the time when they implemented that class.