开发者

How to persist NSColor? There is no alloc for it such as e.g. UIColor alloc

开发者 https://www.devze.com 2023-01-27 06:10 出处:网络
I am trying to port working iPhone code to the Mac (iOS to OSX - I believe?) The working iPhone version is

I am trying to port working iPhone code to the Mac (iOS to OSX - I believe?)

The working iPhone version is

...
return [[UIColor alloc] initWithRed:r green:g blue:b alpha:1.0f];
}

The non-working Mac attempt is

...
return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
}                                       

But when I later access the container, the NSColor is not there. But when I try various versions of [NSColor alloc], none of them "work".

My questi开发者_StackOverflowon is, how do I create an NSColor that persists (so that later, I have to de-allocate it)?


NSColor's +colorWith methods return an autoreleased NSColor instance, so in order to obtain ownership of the object, you can send it the retain message.

-(NSColor *) getSomeColor {
   return [NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f];
}
//...
//somewhere else...
myColor = [[self getSomeColor] retain];

Another point worth mentioning is that according to the Object Ownership Policy, you should not return an object with a retain count > 0 from a method that does not have the words alloc, new or copy.

So in this case, you should return the autoreleased NSColor and send it the retain message on the receiving end.


You need to retain your color in your mac attempt. You are calling a function that returns an autoreleased object. You need to either keep calling this function every time you want a color or do something like this:

return [[NSColor colorWithCalibratedRed:r green:g blue:b alpha:1.0f] retain];


The key here is that you need to own the object. alloc is one message that confers ownership. retain is another. You need to retain the color.

0

精彩评论

暂无评论...
验证码 换一张
取 消