What prevents the autoreleased instance of NSArray from being released before it’s used in the method it’s returned to?
- (NSArray *) f {
return [NSArray array];
}
- (void) g {
NSArray *a = [self f];
// do something with a
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Autorelease pools are per thread. That is, an autoreleased object is, effectively, a delayed call to
releasethat happens on a per thread basis.Thus, if there is no call to
drainbetween the caller and the callee, there is no way the autoreleased object will be released because of a pool drain (barring serious threading stupidity).In general, pools are drained at very well specified times, like Kevin said:
• the run loop will drain the pool at the bottom of each pass through the loop
• dispatched blocks via GCD will execute within a pool context that’ll be drained “every now and then” (implementation detail). NSOperationQueue behaves similarly
• other threads are responsible for doing it themselves
Thus, in your simple example, the code execution is quite linear and, by inspection, there can be no drain in that thread of execution between the return and the use in the caller.
(Note that this is also one of the reasons why
retainCountis useless; it neither accounts for any “delayed release” calls caused byautoreleasenor does it quantify any per-thread retains. In reality, you should think of retains/releases as being entirely per-thread; if you retain an object on a thread you should release it on the same thread unless you are explicitly transferring ownership from one thread to another.)