Re: Core Foundation Objects and Properties when using ARC
Re: Core Foundation Objects and Properties when using ARC
- Subject: Re: Core Foundation Objects and Properties when using ARC
- From: Matt Neuburg <email@hidden>
- Date: Sun, 17 Feb 2013 09:45:35 -0800
On Fri, 11 Jan 2013 10:03:33 -0800, John McCall <email@hidden> said:
>On Jan 10, 2013, at 4:35 PM, Dave <email@hidden> wrote:
>> I've looked all over and just can't seem to find the recommended approach to handling CF objects in properties when using ARC.
>>
>> I have an init method that needs to create a CF object and store it as a property for use while the object is alive. When the object is released I want to release the CF Object,
>>
>> Code:
>>
>> -(id) init
>> {
>> // normal init code
>>
>>
>> CFThingRef myCFThing = CFThingCreate();
>>
>> self.propCFThing = myCFThing;
>> }
>>
>>
>> -(void) dealloc
>> {
>> CFRelease(self.propCFThing);
>> self.propCFThing = NULL;
>> }
>>
>> This code gives analyzer warnings saying that a CF object has leaked.
>>
>> What is the best way to stop the warnings?
>
>This isn't really about ARC. ARC doesn't currently manage objects of CF type.
>
>If the property is really readonly except for initialization, the best pattern is to (1) mark the property readonly and (2) assign directly to the ivar in the -init method. Don't forget to also (3) release the ivar in -dealloc.
I would just add: test your ivar for NULL before CFReleasing it. CFReleasing NULL will crash your code. Been there done that!
Example of a setter (hmm, maybe I should be testing first to make sure that _bitmapContext and bitmap aren't the same object):
if (self->_bitmapContext)
CGContextRelease(self->_bitmapContext);
self->_bitmapContext = bitmap;
Example of dealloc:
- (void) dealloc {
if (_bitmapContext)
CGContextRelease(_bitmapContext);
}
m.
--
matt neuburg, phd = email@hidden, <http://www.apeth.net/matt/>
A fool + a tool + an autorelease pool = cool!
Programming iOS 5! http://shop.oreilly.com/product/0636920023562.do
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden