I am learning Objective-C/Cocoa using the 4th edition of Cocoa Programming for Mac OSX. I apologize for the basic question but I'm one of those people that really need to understand the insides of everything in order for it to make sense to me and this book doesn't always do that to my needs. I've already picked up the basics of C++ and now I'm learning Obj-C so that is my background. This is a snippet of code that I'm learning...
for (i= 0; i < 10; i++) {
NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i * 3)];
[array addObject:newNumber];
}
My question is why would you create instances of NSNumber to add to the array instead of just a single integer variable. It seems like it is just extra overhead creating a new instance each loop that could be avoided. But I'm sure the authors know what they are doing and there is a reason for it, could someone please explain?
[array addObject:@(i * 3)];
. – rmaddyalloc
implies a +1 retain count. TheaddObject:
implies a second +1 retain count. Releasingarray
will release that second +1. But something needs to balance the +1 ofalloc
. If you have ARC enabled, then it'll "just work". If not, then adding[newNumber release];
after theaddObject:
line would be correct. – bbum