开发者

Objective-c simple memory question

If I have a variable in my view controler

viewcontroller.m

@interface MemoryTestViewController : UIViewController
{
    NSMutableArray *array;
}

@end

in my implementation

- (void)viewDidLoad
{
    [super 开发者_如何学CviewDidLoad];

    NSMutableArray *aux = [[NSMutableArray alloc] initWithCapacity:1];
    array = aux;
    [aux release];
    // Do i have to do array release?
}

Do i have to release my variable array somewhere? Theoricaly i havent allocated that variable... I testes the memory leaks and even if i dont release anything the instruments doesn't detect any leak.


No, you don't need to release. All you do is assign the pointer of aux to your array variable. array is invalid at the moment where you release aux. This is probably not as intended. If you want to work with array, you'll have to retain it.


You've already released the array with [aux release]; -- you in fact have the opposite problem to a leak: an over-release.

Assignments in Objective-C are just assignments of pointers; there's no copying or automatic memory management. When you say array = aux;, array now points to the exact same object as aux. If you then get rid of aux by releasing it (and therefore letting it be deallocated), array doesn't point to anything anymore.*

You have a couple of options for fixing this:

  1. (Simplest) Assign the newly-created array directly to array:

    array = [[NSMutableArray alloc] initWithCapacity:1];

    This gives you ownership of the new array, under the name array. Don't release it until you are done with it (possibly in dealloc; certainly not in this method).

  2. (Best) Create a declared property for array and let that mechanism handle the memory management for you:


@interface MemoryTestViewController : UIViewController
{
    NSMutableArray *array;  
}  

@property (copy, nonatomic, setter=setArrayByMutableCopy) NSMutableArray * array;
@end

@implementation MemoryTestViewController
@synthesize array;

// Properties can't automatically make mutable copies, so you need to create
// your own setter method.
- (void) setArrayByMutableCopy: (NSMutableArray *)newArray {
    NSMutableArray * tmp = [newArray mutableCopy];
    [array release];
    array = tmp;
}
...

*Or, rather, it points to a place where there used to be a valid object, which is a great way to make your program crash.


No. Assigning an object to a variable does not retain it. However if you plan to use that variable for a while, you should retain it and release it when you are done with it.

alloc raised the retain counter to 1 and [aux release] set it to 0


You should add a property:

@property (nonatomic, retain) NSMutableArray *array;

and later in your viewDidLoad:

// wrong, leaks: self.array = [[NSMutableArray alloc] initWithCapacity:1];

array = [[NSMutableArray alloc] initWithCapacity:1];

and yes, somewhat later release it, probably in dealloc..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜