Effect "myObj = [[[[MyClass alloc] init] autorelease] save]; '?

I just downloaded the Facebook iOS SDK , and I noticed that in the example code that comes with the SDK, when it creates an instance of the Facebook class, it does it like this:

_facebook = [[[[Facebook alloc] init] autorelease] retain]; 

where _facebook is a member variable of the caller (i.e. not a local variable).

Can someone explain what autorealization is and then save it?

+6
memory-management objective-c iphone facebook
source share
2 answers

It effectively does nothing but consume a few cycles and memory.

Or, more precisely, in a correctly written application does nothing. In an incorrectly written application, it can mask the error, increasing the life of the _facebook object. However, this is not a real solution.

I found a similar line of code in http://github.com/facebook/facebook-ios-sdk/blob/master/sample/DemoApp/Classes/DemoAppViewController.m If this is what you are talking about, yes, this is nonsense.

+13
source share

Although it is possible that the code you found was just inaccurate, this template makes sense.

"alloc, autorelease, keep" means that the object is referenced in two places:

  • As the return value in the call stack (auto-pause style)
  • FB SDK itself ("Save")

This is important if two links can be released independently. For example, if the SDK can release its link before the call stack has completed and lowered the auto resource pool. Well, that's pretty subtle; what I mean?

Consider the following cases:

A) actual code

 _facebook = [[[[Facebook alloc] init] autorelease] retain]; 

_facebook now has a hold count of 2 and expects 2 calls to β€œrelease”: 1 from whoever calls β€œsave,” and 1 at some point in the future when NSAutoreleasePool is depleted.

B) a simple "alternative" option (NOT equivalent)

 _facebook = [[Facebook alloc] init]; 

_facebook has a hold value of 1 and will be destroyed when calling 'release' (potentially a big problem if the autocomplete pool is not exhausted yet and the call stack still uses the object)

Why does it matter? Imagine this code:

 @implementation (Thinger) +(id) make_new_thing { return my_copy_of_thing = [[[[Thing alloc] init] autorelease] retain]; } +(id) forget_about_thing { if (my_copy_of_thing != nil) { [my_copy_of_thing release]; my_copy_of_thing = nil; } } @end void foo() { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; id thing = [Thinger make_new_thing]; [Thinger forget_about_thing]; ... [thing useThing]; // implementation B would break here ! [pool drain]; } 
+1
source share

All Articles