When the class creates an object through the alloc method, does the object's reference count change to 1?

67 views Asked by At

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

There are 2 answers

3
Yun CHEN On

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;
}
0
Kira On

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;