Search code examples
objective-ccocoacopynsimage

Why isn't the name property of my NSImage being copied when I call `-copy`?


I have an NSArray ("objects") that contains objects of type NSImage

I have found that when I try to make a copy of each image in the array, the name property on the NSImage does not get copied.

   for (NSObject* object in objects)
   {
      NSMenuItem* menuItem = nil;
      if ([object isKindOfClass:[NSImage class]])
      {
         NSImage* image = [object copy];
         //Breakpoint here

Here is a screenshot of my variable view at the breakpoint above ^^

enter image description here

How could it be that the name property isn't being copied?


Solution

  • Name on images is used as a special registration mechanism so you can look the images up by name later. As such you can only have one image with each name. If you change the name on an image then the original registration is removed and the new one added. If an image already have the name you try to set then the set is declined.

    Effectively what you're seeing is an attempted re-registration of an image name against a different image. That image might be a copy, so you might think it's fine to keep the name, but you don't know what the private implementation is and you also aren't considering potential mutable subclasses.

    So, you can't share names across multiple different images. If you want to do something similar then you need to manage the names / identifiers separately using a custom scheme / approach.