0

When we call alloc with a Class, Whether the object's reference count will be 1.

For example:

NSObject *obj = [NSObject alloc];

After this line of code is executed, the reference count of the object is 0 or 1?

I read the alloc source code, But did not find the alloc method will have any action on the object's reference count,At this point the object of the reference count is still 0?

if 0, then the object will be destroyed, but if not 0, how it is achieved,

I hope someone can help me answer the hearts of confusion, thank you!

Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
  • Are you still before ARC? ARC can help you with that, but usually after you do alloc in a object, it gets a reference 1. To manage this, if you are before ARC, you can use the autorelease or dealloc to give 0 to the object again. – Pedro Pinho Jul 18 '17 at 10:04
  • Thank you for the optimization of my format, I was recently in the time to read the source of such a confused, do not know in the "alloc", the object of the reference count is 1, because I did not find the effective confirmation of this problem Code – Rush to ask the way Jul 18 '17 at 10:10
  • This is my friend made an article, I also read, but still failed to solve the confusion in my heart – Rush to ask the way Jul 18 '17 at 10:20
  • @Rushtoasktheway Implementation detail; the retain count of an object is stored in the `isa` of the object. On allocation, the `isa` is initialized to contain a reference to the class, a retain count of 1, and some other metadata. Unless the class implements customer retain/release. All of which is an implementation detail and, while interesting, the retain count is utterly useless for debugging or development purposes. – bbum Jul 18 '17 at 15:55

1 Answers1

2

alloc creates the object with a reference count of 1. It doesn't create it with a reference count of 0 and increases the reference count. First, that would be inefficient (one extra retain call for each object created), and second, it wouldn't work, because once an object has a reference count of 0, Objective-C will absolutely definitely deallocate the object; there is no way to stop the deallocation, and one side effect of that is that you cannot increase or decrease the reference count of an object with zero reference count.

gnasher729
  • 51,477
  • 5
  • 75
  • 98