Do I need to explicitly alloc my NSNumber?

后端 未结 3 604
小蘑菇
小蘑菇 2020-12-31 16:17

I am defining a number, as follows:

NSNumber *nn0 = [NSNumber numberWithInt:0];

It works fine without any alloc. My understanding is that i

3条回答
  •  一个人的身影
    2020-12-31 17:06

    Just follow the core memory-management rule: If you "own" the variable, you have to eventually relinquish ownership. You take ownership by: creating the object (alloc/new/copy) or specifically taking ownership (retain). In all these cases, you're required to release it.

    If you need the object to stick around, you need to take ownership of it. So if you know you only need the number for this method (like to pass it into an array or whatever), use the convenience method and just leave it at that. If you want to keep the number for some reason (and instance variable, for example), then you can safely alloc/init it.

    If you release something that you don't own, you will get a runtime error.

提交回复
热议问题