What is the difference between releasing and autoreleasing?

后端 未结 4 1071
北海茫月
北海茫月 2020-12-08 12:10

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 somet

4条回答
  •  粉色の甜心
    2020-12-08 12:34

    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.

提交回复
热议问题