Why is the retainCount still 1 after [object release]?

后端 未结 5 1254
Happy的楠姐
Happy的楠姐 2021-01-19 07:13
NSLog(@\"first:%u\",[object retainCount]);
[object release];
NSLog(@\"second:%u\",[object retainCount]);

Output:

first:1
second:1
相关标签:
5条回答
  • 2021-01-19 07:23

    a Quote from NSObject reference on retainCount method

    This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

    0 讨论(0)
  • 2021-01-19 07:25

    Object can be released but not when you think it will be. Basically, don't look at retainCount. It may not change until the next runloop or at all, it's an implementation detail. You will get a sense for when you need to release and when you don't with experience but until then rely on the clang analyzer.

    0 讨论(0)
  • 2021-01-19 07:31

    Divide any number by zero and you will find the meaning of "object with retain count of zero".

    0 讨论(0)
  • 2021-01-19 07:31

    I agree with the other comments about not using retainCount to get a reliable count.

    EDIT: Ignore my stupidity below... :)

    However, I've observed that setting the corresponding property to nil...

    self.object = nil;
    

    the retainCount does tend to be decremented immediately.

    0 讨论(0)
  • 2021-01-19 07:37

    First, retainCount doesn't give you a number you can use. It's meaningless.

    Second, the reason the retainCount is 0 is probably that you try to work with an object that doesn't exist anymore. You're lucky your application doesn't crash, because your accessing invalid memory. Decreasing the retainCount just before deallocating an object is unnecessary, therefore Apple doesn't do it, probably.

    0 讨论(0)
提交回复
热议问题