Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the new pattern for releasing self with automatic reference counting?

Using the NSObject method -(id)awakeAfterUsingCoder:(NSCoder *)decoder as an example, the documentation says:

Allows an object, after being decoded, to substitute another object for itself. For example, an object that represents a font might, upon being decoded, release itself and return an existing object having the same font description as itself. In this way, redundant objects can be eliminated.

Normally you would do

[self release];
return substitutedObject;

With ARC you have to leave this line out. Wouldn't this leak? Or should I just trust the NSCoder object to release the original object for me? If so why would you have to explicitly release self with non-ARC code in the first place?

I don't think self = nil is correct in light of what the compiler documentation says about self: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#misc.self

like image 643
jamesmoschou Avatar asked Apr 22 '12 02:04

jamesmoschou


1 Answers

A similar issue arises in the context of NIB top-level objects on Mac OS X. The Resource Programming Guide says:

If the File’s Owner is not an instance of NSWindowController or NSViewController, then you need to decrement the reference count of the top level objects yourself. With manual reference counting, it was possible to achieve this by sending top-level objects a release message. You cannot do this with ARC. Instead, you cast references to top-level objects to a Core Foundation type and use CFRelease.

So, that technique can presumably be used in this situation, too. CFRelease((__bridge CFTypeRef)self);

like image 156
Ken Thomases Avatar answered Oct 15 '22 07:10

Ken Thomases