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 source code, I can't find some code that the alloc
method for any operation on the reference count. If the object of the reference count 0, the object will be destroyed, if it is 1, then it is how to achieve, whether someone can help solve the confusion, thank you!
2 Answers
In MRC mode, alloc
method creates object and the reference count will be calculated to 1. Means the class created the object and retained it.
If you create local object in a method , and forget to release it, the memory will be leaked. You need to release it manually: [obj release];
.
Ocne an object alloced, there is no operation for setting retain count to 1. Because the method for caculating reference count will return 1 if there is no other class retained the object. If another object retains the current object, the current object's reference table will save that retaining. Then the result will be increased by calculation. The method source:
uintptr_t
objc_object::sidetable_retainCount()
{
SideTable& table = SideTables()[this];
size_t refcnt_result = 1;
table.lock();
RefcountMap::iterator it = table.refcnts.find(this);
if (it != table.refcnts.end()) {
// this is valid for SIDE_TABLE_RC_PINNED too
refcnt_result += it->second >> SIDE_TABLE_RC_SHIFT;
}
table.unlock();
return refcnt_result;
}

- 6,450
- 3
- 30
- 33
-
I read the "alloc" source and found that it is only in memory to open up a space to the object, and there is no reference to the object count any operation, then the object of the reference count is 1 from where? – Rush to ask the way Jul 18 '17 at 08:44
-
The method you provide is a method that will be executed when the object is used with "retainCount". If I do not call the "retaionCount" method, this method would not want to be executed, so when I call the "alloc" method Time, and did not implement this method. – Rush to ask the way Jul 18 '17 at 09:51
-
Of course, it should be like this. Only when you need the "retainCount", it calculates for you. That's why you didn't see "retainCount" operation when alloc. I guess this method will also be called when you call [obj release], the object will be considered to destroy if the result is 1(become 0 after release). – Yun CHEN Jul 18 '17 at 14:23
It's retain count is 1 until out of it's block; And one more object needs it , it's retain count will increase by 1. It will exist till no one needs it;

- 243
- 2
- 9