Simple Question about NSObject class / Retain Count
If I create an NSObject class with a method that returns an NSMutableArray do I need to release the array inside the class or does the Class never retain?
Not sure on how to explain so here is some code:
@implementation PointsClass
- (NSMutableArray *)pointsForLevel
{
NSMutableArray *_points = 开发者_如何学编程[NSMutableArray new];
[_points addObject:[NSValue valueWithCGPoint:CGPointMake(521, 279)]];
[_points addObject:[NSValue valueWithCGPoint:CGPointMake(321, 491)]];
[_points addObject:[NSValue valueWithCGPoint:CGPointMake(419, 477)]];
return _points;
}
@end
If i call this method from a ViewController like this:
PointsClass *pointsClass = [PointsClass new];
NSMutableArray *points = [pointsClass pointsForLevel];
[pointsClass release];
Do I only need to release the pointers Array? Has the _points array been retained at all?
new will give you an object with a retain count of 1. So, yes, you do need to balance this with a release somewhere.
The convention here is to return [_points autorelease] and then let the caller decide if he needs to retain the array for some period of time.
Apple's Memory Management Programming Guide (which you should absolutely read) sums it up best:
- You only release or autorelease objects you own.
- You take ownership of an object if you create it using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message.
- You use release or autorelease to relinquish ownership of an object. autorelease just means “send a release message in the future” (specifically: when the used autorelease pool receives a drain message—to understand when this will be, see “Autorelease Pools”).
Because you created it with "new", you are responsible for releasing it. I would recommend instead, one of the following:
- autorelease _points before returning it. The caller can then decide whether to retain it or not, or...
- rename your method to reflect the fact that the object returned by it must be release (like newPointsForLevel).
In addition, you're creating an instance of PointsClass (via new), and not assigning it to a variable. That's a memory leak.
A couple other pointers:
- alloc/init is generally preferred over new, although they are functionally identical. See here for more info on the topic.
- I wouldn't recommend naming local variables with a leading underscore - that's usually reserved for instance variables.
精彩评论