Question

I recently moved from manual reference count environment to an ARC environment in iOS project.

So let's say that I had the following code in the past of my manual reference count environment:

// Manual reference count environment (using "alloc" prefix as method returns a retained NSArray)
- (NSArray *)allocMyArray {
    NSArray *array = [[NSArray alloc] initWithObject:@"this is just a sample code"];

    return array;
}

Can I change the above method name in a full ARC environment from allocMyArray to myArray?

Is the following code has a valid naming convention and also isn't leaking in ARC environment?

// ARC environment
- (NSArray *)myArray {
    NSArray *array = [[NSArray alloc] initWithObject:@"this is just a sample code"];

    return array;
}

In general, should I ever use the "alloc" or "new" method prefix in a full ARC environment or is this naming convention is meaningless in ARC environment and has no effect on the compiler?

Thanks, Yoash

Was it helpful?

Solution

If you're using ARC, there's not that much of a difference between alloc init and using a class method. If you're not using ARC, the difference is extremely important.

The alloc/init combination gives you an owning reference. That means you must release it later on. The classnameWithFoo variant returns a non-owning reference (auto released). You may not release it.

This follows the usual Cocoa naming conventions. All methods return non-owning (autoreleased) instances, except for the methods that start with alloc, copy, mutableCopy and new. These return owning references that you must release.

The naming convention you suggest for the ARC environment is good, and the code will not leak.

The object will only be around until the run loop ends though.

Where as if you return an alloc/inited object, ARC will insert the appropriate release calls and the object will exist for it's scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top