The second is better.
From the Memory Management Programming Guide:
- You own any object you create.
- You “create” an object using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy).
Since your getter method doesn't match any of those criteria it should not make caller the owner of the returned object implicitly. Callers should explicitly invoke retain
on the returned value if they want to own it.
That being said, you don't need the NSAutoreleasePool
in your code because, by default, the run loop already has a pool. With that, the following should suffice:
- (Employee*) getCustomEmployee {
Employee *emp = [[[Employee alloc] init] autorelease];
// do something with emp
return emp;
}
- (void) process {
Employee *emp = [self getCustomEmployee];
// do something with emp
}
Other answerers say that you should not be allocating new objects in getters. I disagree with that. Creating objects on demand is a good practice in many cases. Specifically when you have resource intensive objects that may never need to be allocated. It's perfectly acceptable to allocate new objects in a getter so long as the ownership rules are adhered to.
In this case, if the employee can be shared between multiple callers, then you might want to consider lazy-initialization. The following code assumes that you have an instance variable (a ivar in objective-c lingo) called _employee.
- (Employee*) getCustomEmployee {
@synchronized(self)
if (!_employee) {
_employee = [[Employee alloc] init];
}
}
return _employee;
}
- (void) dealloc {
[_employee release];
}
- (void) process {
Employee *emp = [self getCustomEmployee];
// do something with emp
}
In this case the ownership stays with the object that created it, therefore it must release the memory at some point in the future. The natural place for releasing owned objects is when the object itself is released. When that happens the dealloc
method will be called, so that's where we can do our cleanup.