I have a question that may not be of any practical use right now since ARC is highly encourage, but I'm studying memory management and there's something I didn't quite understand.
I have this method
+(NSNumber *)releaseTooEarly
{
NSNumber *createdNumber = [[NSNumber alloc] initWithInteger:5];
NSLog(@"retain count before release: %d", createdNumber.retainCount); //Prints 2
[createdNumber release];
NSLog(@"%@", createdNumber); //Prints 5
return createdNumber;
}
- If the object was just created, should the retain count be 1 instead of 2?
- I understand that in this kind of situations I should use autorelease so I can return the value, and the caller can make use of it before it is deallocated. I though that if I use retain instead it would immediately deallocate the object, but the next NSLog shows that it still exits, and the value is successfully returned.
I'm wondering if I'm inside an autorelease pool that is not allowing me to deallocate the object within the function.
I know I should be using ARC but I just want to understand the reason of this results.