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

前端 未结 2 441
春和景丽
春和景丽 2021-01-01 04:48

The code I\'m currently working on requires adding an NSNumber object to an array. All of the NSNumbers with value 0-12 are added fine, but 13 onward causes a EXC_BAD_ACCESS

相关标签:
2条回答
  • 2021-01-01 05:43

    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).

    0 讨论(0)
  • 2021-01-01 05:45

    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.

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