NSNumber >= 13 won't retain. Everything else will

半城伤御伤魂 提交于 2019-11-30 15:32:09
paxdiablo

The numbers 0 through 12 are special as I discovered when answering another question here. Keep in mind that this is an implementation detail, not a language specification thing.

Basically, numbers up to (and including) 12 give you a reference to an already existing NSNumber, something which is possible due to the fact that they're immutable. Investigation showed that numbers 13 or greater gave a separate instance.

So you probably have screwed up your memory management after all :-) It's just that the fact that numbers less than 13 are likely references to numbers already in existence that's saving your bacon in those cases. I suggest you post more code so that we can track down that specific problem.


And based on your comment to another answer here:

I added a retain line into the code and everything works perfectly now. No idea why. I'm just going to roll with it. Thanks!

I think you'll find that the fact that NSNumbers less than 13 already have a retain count of 1 before you get your own (bumping the count up to 2) is why they're not causing the EXC_BAD_ACCESS. Obviously your code is losing all the numbers you allocate, but the system isn't freeing those under 13 since they're still in use (retain count of 1 or more).

Clearly NSNumbers >12 will retain. I suggest that you write a very small program that proves this to yourself. Then take that program, make it a function, and call it early in your program. Slowly move the function to later points in your program until the error appears. You will thus find your real bug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!