When does autorelease actually cause a release in Cocoa Touch? - cocoa-touch

I understand you need to be careful with autorelease on iOS. I have a method that is returning an object it allocs which is needed by the caller, so in this situation -- as I understand it -- I need to send autorelease to the object in the callee before it returns.
This is fine, but once control returns to the phone (i.e. after my button click has been processed) it seems that the autorelease pool is released. I suspect this is how it is supposed to be, but I am wondering what is the best practice for this situation.
I have resorted to sending a retain message from the caller so that the object is not released and then explicitly releasing it in dealloc.
Is this the best approach?

The autorelease pool is typically released after each iteration of the run loop. Roughly, every Cocoa and Cocoa Touch application is structured like this:
Get the next message out of the queue
Create an autorelease pool
Dispatch the message (this is where your application does its work)
Drain the autorelease pool
What you describe is the expected behavior. If you want to keep an object around any longer than that, you'll need to explicitly retain it.

Using autorelease is a way of saying, "Object, I don't want you anymore, but I'm going to pass you to somebody else who might want you, so don't vanish just yet." So the object will stick around long enough for you to return it from a method or give it to another object. When some code wants to keep the object around, it must claim ownership by retaining it.
See the memory management guidelines for everything you need to know to use autorelease correctly.

Here is an examle provided in the Apple Memory Management document:
– (id)findMatchingObject:(id)anObject
{
id match = nil;
while (match == nil) {
NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
/* Do a search that creates a lot of temporary objects. */
match = [self expensiveSearchForObject:anObject];
if (match != nil) {
[match retain]; /* Keep match around. */
}
[subPool release];
}
return [match autorelease]; /* Let match go and return it. */
}

Yes, that's the best approach. Autorelease is really only intended for interactions in code that you know. Once you're storing an object, you should either know that the object that holds a reference will not die/go out of scope until you're also done with the object, or you need to retain the object.

It is only guaranteed that autoreleased objects will be released after the end of your method. After all, the method that called your method could have created its own pool and release it right after your method.

Related

Why dose the NSString become NSZomie in this code?

I just ran into a problem.I use NSMutableArray to keep the Ad ids that need to be loaded. When one id is preloaded, I remove it from the array. Then I find out that, after remove, the unit id became a zombie.
I tried to reproduce this, and I find out that when the Ads id was pulled from array, it is not a zombie.It just become zombie after removed from array. But, there is still a NSString* refer to it, how can this happen? And If it will become zombie at this point, it should become zombie every time. But it only happens occasionally.
-(void)preloadNextRewardVideo
{
if([_allRewardVideoAds count])
{
NSString* adsName = [_allRewardVideoAds objectAtIndex:0]; //the element is not a zombie here
GADRewardBasedVideoAd* ads = [self ensureRewardVideo:adsName];
if(![ads isReady])
{
_currentRewardVideoName = adsName;
[_allRewardVideoAds removeObjectAtIndex:0];
GADRequest *request = [GADRequest request];
[ads loadRequest:request withAdUnitID:adsName]; //here, adsName is a zombie
_isRewarLoading = YES;
}
}
}
It's worth taking a close look at cocoa's memory management policies. The thing here (it seems to me) is that when your code assigns the string adsName, the object the preloadNextRewardVideo method is part of doesn't take ownership of the string-object that adsName is pointing at ('ownership' in this context means either allocating and initializing space for it through alloc/init, new, copy, etc, or sending it an explicit retain message). All you have is a local variable that points at a string-object owned by the _allRewardVideoAds array. Yes, making the assignment increases the retain count, but that retain is autoreleased, and limited to the scope of this method. As soon as this method ends, nothing is going to own that string-object, and it will deallocate.
This would not be an issue (and would not create the NSZombie flag) except that you just sent adsName to a different object (GADRewardBasedVideoAd* ads) that I'm guessing does not retain it either. Of course, ads is also autoreleased (nothing owns it outside of this method), but what is that, a race-condition over whether ads or adsName is deallocated first? I suspect you do have a race-condition because NSZombie only shows up sometimes, but I don't know enough about the internal mechanisms of autorelease to know how that might work.
I think NSZombie is just telling you that you have an object that is:
in use by an external object, and
due to be destroyed shortly though autorelease.
ARC is anticipating a problem, and using NSZombie to let you know.
You could fix this either by using the property setter (e.g. use self.currentRewardVideoName = adsName) which retains the string-object globally for this object, or by locally copying it (NSString* adsName = [[_allRewardVideoAds objectAtIndex:0] copy]) which makes sure that your object owns the string to the end of the method.
Since you don't enable ARC that means you need to manually manage the memory by yourself. Since you don't enable ARC that means you need to manually manage the memory by yourself. Even though most of APIs will return an auto released object from a method but that's not always be the case.
For this case, NSArray retains the objects contained in itself so it may not need to return an auto released object from objectAtIndex: method since it should be retained by itself as an optimization. In this case I suggest you to call retain the object when you get it from the array and release it before the end of this method. That would help for this case.

iOS objective-c return object availability/scope

I've read apple documentation to assert that I was doing the memory management correctly but some questions raised.
Question 1:
They exhibit this code snippet as wrong :
in obj implementation:
- (NSString *)method1 {
NSString *string = [[NSString alloc] initWithFormat:#"%# %#", firstName, lastName];
return string;
}
... later ...
NString* myString = [obj method1];
NSLog("%#", myString);
[myString release];
Apple Doc :
You own the string returned by alloc, but lose the reference to it before you get a chance to relinquish ownership. Following the memory management rules, this would result in a memory leak, since the caller has no indication that they own the returned object.
Since I'm taking care of releasing the object that has been allocated previously, there is no memory leak, right ? What do they mean by "lose the reference to it" ?
It is wrong only regarding apple's memory management recommendations (the caller has no indication that they own the returned object) or this is also technically wrong ?
Question 2 :
This is about autoreleased objects availability :
Example code:
in obj1 implementation:
- (NSString *)methodA {
NSString *string = [[NSString alloc] initWithFormat:#"%# %#", firstName, lastName];
return [string autorelease];
}
in obj2 implementation:
- (NSString *)methodB:(NSString *)inputString {
NSLog("%#",inputString)
//*other call of methods with arg inputString*//
}
... later ...
NString* myString = [obj1 methodA];
[obj2 method2:myString];
How far (or deep) following my functions calls will the autorelease object returned by obj1 will be available. Regarding apple's documentations "Autorelease objects will be available within their variable scope". Should I retain it at some point ?
Q1: It is wrong only regarding apple's memory management recommendations (the caller has no indication that they own the returned object) or this is also technically wrong ?
Technically this is correct as you release myString after using it. However if you follow Apples guidelines for method naming (strongly recommended), this is clearly wrong:
You own any object you create.
You “create” an object using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy).
method1 doesn't contain create, alloc, new or copy - thus per the guideline the caller doesn't own the object and doesn't have to release it.
Q2: How far (or deep) following my functions calls will the autorelease object returned by obj1 will be available. Regarding apple's documentations "Autorelease objects will be available within their variable scope". Should I retain it at some point ?
Auto-released objects will be alive until the closest Autorelease Pool is drained, see Autorelease Pools:
An autorelease pool is an instance of NSAutoreleasePool that “contains” other objects that have received an autorelease message; when the autorelease pool is deallocated it sends a release message to each of those objects. An object can be put into an autorelease pool several times, and receives a release message for each time it was put into the pool. Thus, sending autorelease instead of release to an object extends the lifetime of that object at least until the pool itself is released (the object may survive longer if it is retained in the interim).
...
The Application Kit automatically creates a pool at the beginning of an event cycle (or event-loop iteration), such as a mouse down event, and releases it at the end, so your code normally does not have to worry about them. There are three cases, though, where you might use your own autorelease pools:
...
So, if you need your instances to stay alive after the corresponding autorelease pool was drained, take ownership by retaining them. Otherwise you usually just let them be handled by the pool.
Since I'm taking care of releasing the object that has been allocated previously, there is no memory leak, right ?
right
What do they mean by "lose the reference to it" ?
you hold no pointers for the object, such that the object may not be accessed in your program.
It is wrong only regarding apple's memory management recommendations (the caller has no indication that they own the returned object) or this is also technically wrong ?
also correct. the static analyzer will prolly cry too
How far (or deep) following my functions calls will the autorelease object returned by obj1 will be available. Regarding apple's documentations "Autorelease objects will be available within their variable scope". Should I retain it at some point ?
this is a little more complex. autorelease pools are stacked upon each other by thread. that's why you must create one when entering a thread or new event loop iteration, and also why it is a good idea to create them explicitly when performing large operations which create many (autoreleased) allocations.
finally the last pool in the stack (for the thread) is destroyed at the end of the run loop's iteration.
if the object is created under an autorelease pool you create explicitly, then you must retain it to use it beyond the lifetime of the pool which it was created in.
similarly, you must formally retain/copy when passing to other threads. typically, this happens immediately - you just create a copy or retain the formal arguments when entering the implementation of the secondary thread.

Memory Management Autorelease vs. Alloc Question

3 correlated questions:
1.Do the code snippets below provide the very same results in terms of memory?
NSBundle *bundle=[[NSBundle alloc] init];
[bundle release];
bundle=nil;
and
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
NSBundle *bundle=[NSBundle mainBundle];
[pool drain];
pool=nil;
bundle=nil;
2.Why in
NSBundle *bundle=[[NSBundle alloc] init];
[bundle release];
the retainCount of bundle is 1, not 0?
3.Which is recommended: always use class methods, or always gain ownership by using alloc?
Thanks.
Yes, those should be equivalent in terms of memory management, from the developer's point of view. The frameworks might be doing something behind the scene to hang on to [NSBundle mainBundle], but that's not your concern.
Ignore retainCount. waves hand That's not the method you're looking for. Once you have relinquished ownership of an object, either by invoking release or autorelease, then it is invalid (bad practice) to send more messages to that object. In your example, you alloc an NSBundle, so you own it. That means it has a +1 retain count (I say +1, because it's relative). When you release the bundle, it now has a "0" retain count, which means you no longer own this object (despite whether or not it may still exist in memory), which means you should not send messages to it, under penalty of stuff blowing up in your face.
What's recommended is to use whatever's appropriate for the situation. If you just need a temporary object, then using a class method that returns an autoreleased object is probably going to be just fine. If you need to be absolutely sure that the object isn't going to go away while you're using it, then you can use an alloc/init approach (or retain an autoreleased object) and then just release it when you're done.
In the second example you will create 1 extra object (the NSAutorealeasePool) and because of that the two are not exactly the same in terms of memory. But after the code runs I believe the memory will return to the same state in both examples. I am not really sure but I believe that in the second example bundle is an autoreleased object, so when the pool is drained it gets released.
I believe that when the object gets dealloc'ed the retainCount isn't changed.
It is usually recommended to avoid class methods when you create a lot of temporary objects because they won't get released until the next AutoreleasePool drain is called (and if you don't have an AutoreleasePool inside your method it won't happen for sure until you return from your method - and maybe even later). Otherwise you should use the one that feels better for you. I personally prefer allocating them. It is also important to remember that if you want the autoreleased object (the one returned from a class method) to stick around even after you return from the function to retain it.

What is the difference between releasing and autoreleasing?

I still have some unclear understand about release and autorelease. What are the difference between both of them? I have this code. For facebook connection. I crash it sometimes when I go to Facebook login, I doubting maybe it is because I don't release the object nicely.? Thanks for any helps
if (_session.isConnected) {
[_session logout];
} else {
FBLoginDialog* dialog = [[[FBLoginDialog alloc] initWithSession:_session] autorelease];
[dialog show];
}
The Memory Management Programming Guide for Cocoa will soon be your best friend. In brief, object instances in Cocoa are memory managed using reference counting (unless, of course you're using garbage collection on OS X). An object indicates that it wants to 'retain' an ownership interest in an other instance--keep it from being deallocated--by sending it a -retain message. An object indicates that it wants to release that interest by sending the other instance a -release message. If the number of objects that have 'retained' and ownership interest in an object drops to 0 (i.e. when the last of the owning instances sends a -release message), the instance with a 0 retain count is deallocated.
It's sometimes convenient to say "I want this instance to be released some time in the future". That's the purpose of -autorelease. Sending an -autorelease message adds the receiver to the current NSAutoreleasePool. When that pool is drained, it sends a -release message to all the instances in the pool. An NSAutoreleasePool is automatically created at the start of each iteration of each thread's run loop and drained at the end of that iteration. Thus, you can do something like this in a method:
- (id)myMethod {
return [[[MyObject alloc] init] autorelease];
}
The caller of this method will get back an instance that they can -retain if they wish to keep it. If they don't retain it, it will stick around at least until the enclosing autorelease pool is drained:
- (void)someOtherMethod {
...
id instance = [obj myMethod];
... // do more with instance, knowing that it won't be dealloc'd until after someOtherMethod returns
}
Releasing means you release that right away.
Autoreleasing means you want the variable to be released on the next autorelease pool.
You use autorelease when you want to keep retaining the variable but don't want to create a memory leak. You use release when you don't need the variable anymore.
Sample:
- (NSNumber *)return5 {
NSNumber * result = [[NSNumber alloc]initWitnInt: 5];
[result autorelease];
return result;
}
Why do we use autorelease there?
If we use [result release] instead, variable result will be destroyed AT that time. Which means that the returned value will be garbage.
If we do not release at all, variable result will be hold FOREVER incurring memory leak.
We can tell every caller to the function to release result but that would be a headache and prone to error.
So we use autorelease. We mark the variable to be released on the next autorelease pool. Basically we mark the variable to be released near the alloc. Hence the mantra alloc is paired with release in the same function holds all the time.
Actually, you'll do fine changing all release into autorelease. Your memory use won't be efficient, however, the effect is minimal. All variables, in all programming language is effectively autoreleased.
Anyway, use ARC.
background discussion:
objective-c is reference counted, so objects are deleted when the reference count reaches 0. release reduces the reference-count immediately, autorelease reduces it when the autorelease-pool is popped
when to use:
use autorelease when allocating the object if
you do not need it after the current function
it will be retiained by some other objet/function and will be released by a later by the retaining code
when the logic of the current function is tricky, so you would have to send release in a dozen different places before doing a return
use "manual" release
to revert a previous retain (in case you are implementing a library)
if you need precise control of freeing objects (e.g. they use lots of memory or the autorelease pool will not be popped for some time)
but really my freand:
read the Memory Management Programming Guide for Cocoa as suggested by Barry and run your code with instruments (zombies and leaks) often to catch any and almost all memory management errors.
Erik
According to the Memory Management Programming Guide for Cocoa:
The autorelease method, defined by
NSObject, marks the receiver for later
release. By autoreleasing an
object—that is, by sending it an
autorelease message—you declare that
you don't want to own the object
beyond the scope in which you sent
autorelease.
Also:
The autorelease method thus allows
every object to use other objects
without worrying about disposing of
them.

Differences in return object pointer?

Can someone explain the difference between these two, the first one is taken from allowing xcode to automatically generate the declaration, the last one is taken from an example in "Cocoa Programming" by Aaron Hillegass.
- (NSString*)planetName {
return [[planetName retain] autorelease];
}
.
- (NSString*)planetName {
return planetName;
}
I am just curious whats going on, my understanding was that the method is returning a pointer to either nil or an existing string object. I don't understand the reason for retaining and then adding to the autorelease pool?
Consider:
NSString *planetName = [myPlanet planetName];
[myPlanet setPlanetName: #"Bob"];
[planetName length];
Without [[planetName retain] autorelease], the above will very likely crash.
retain/autorelease puts the object into the current thread's autorelease pool. That effectively guarantees that the object will remain valid until the pool is drained, which is typically after the current event -- user event, timer firing, etc... -- is done processing.
(1) Use #property and #synthesize. It generates correct getter/setters for you.
(2) Read the Cocoa Memory Management guide. It answers all of these questions quite well.
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
In both cases, yes, they are both returning a pointer to either nil or the string object.
The difference is that the first code block handles memory management, the second does not. The second code block is assuming you are managing planetName somewhere else in your class instance, whereas in the first code block Apple is being as conservative as possible in keeping that memory from leaking. By putting the memory in the current autorelease pool it will be destroyed with the pool.
My recommendation would be to stick with the latter case and to be a little wiser about managing your own object instances than what XCode is auto-generating for you.