When to use -retainCount?

2018-12-31 00:43发布

I would like to know in what situation did you use -retainCount so far, and eventually the problems that can happen using it.

Thanks.

11条回答
春风洒进眼中
2楼-- · 2018-12-31 01:28

The examples used in Dave's post are NSNumber and NSStrings...so, if you use some other classes, such as UIViews, I'm sure you will get the correct answer(The retain count depends on the implementation, and it's predictable).

查看更多
一个人的天荒地老
3楼-- · 2018-12-31 01:29

Take a look at the Apple documentation on NSObject, it pretty much covers your question: NSObject retainCount

In short, retainCount is probably useless to you unless you've implemented your own reference counting system (and I can almost guarantee you won't have).

In Apple's own words, retainCount is "typically of no value in debugging memory management issues".

查看更多
梦该遗忘
4楼-- · 2018-12-31 01:29

Of course you should never use the retainCount method in your code, since the meaning of its value depends on how many autoreleases have been applied to the object and that is something you cannot predict. However it is very useful for debugging -- especially when you are hunting down memory leaks in code that calls methods of Appkit objects outside of the main event loop -- and it should not be deprecated.

In your effort to make your point you seriously overstated the inscrutable nature of the value. It is true that it is not always a reference count. There are some special values that are used for flags, for example to indicate that an object should never be deallocated. A number like 1152921504606846975 looks very mysterious until you write it in hex and get 0xfffffffffffffff. And 9223372036854775807 is 0x7fffffffffffffff in hex. And it really is not so surprising that someone would choose to use values like these as flags, given that it would take almost 3000 years to get a retainCount as high as the larger number, assuming you incremented the retainCount 100,000,000 times per second.

查看更多
骚的不知所云
5楼-- · 2018-12-31 01:30

What problems can you get from using it? All it does is return the retain count of the object. I have never called it and can't think of any reason that I would. I have overridden it in singletons to make sure they aren't deallocated though.

查看更多
刘海飞了
6楼-- · 2018-12-31 01:31

You should never use it in your code, but it could definitely help when debugging

查看更多
听够珍惜
7楼-- · 2018-12-31 01:32

Never use the -retainCount in your code. However if you use, you will never see it returns zero. Think about why. :-)

查看更多
登录 后发表回答