开发者

Storing custom alloc'ed objects in an array. Memory Management

I am not sure if I am writing this code correctly.

Fruit * o1 = [[Fruit alloc] initWithName:kFruitOrange imageView:orange1] ;
fruitArray = [[NSMutableArray arrayWithObjects:o1, nil] retain]; // retain array for later use.

There are actually several fruits. Since I alloc them, then assign them to an array in my class init method. When and how should I release these objects.

CLARIFICATION. If I release [o1 release] after saving in array, I get "exc_bad_access" errors when looking at the array in other methods.

In my viewDidUnload method, I have gone through the array and released each object manually.

  for (Fruit * f  in fruitArray) {
        [f release];
    }

I have never seen anyone else do this in code before, so I am thinking that this is not the correct way to do it?

UPDATE

-(Fruit *) initWithName:(enum fruitTypes)fruitName imageView:(UIImageView *)iv{
    if((self = [super init])){
        name = @"Fuit Object";
        NSLog(@"creating orange colour %i", fruitName);
        switch (fruitName) {
            case kFruitOrange:
                 NSLog(@"creating orange colour ");
                colour = [UIColor orangeColor] ;
                break;
            case kFruitBanana:
                colour = [UIColor yellowColor];
                break;
            case kFruitKiwi:
                colour = [UIColor greenColor];
                break;
            case kFruitBlue:
                colour = [开发者_Python百科UIColor blueColor];
                break;
            default:
                NSLog(@"COLOUR NOT FOUND");
                break;
        }
        value = fruitName;
        imageView = iv;
        center = iv.center;


        [colour retain];
        [imageView retain];
        [name retain];


        return self;
    }
    return nil;

}

** ANSWER WAS I NEEDED TO RETAIN THE VARIABLES I SET IN MY FRUIT.M CLASS.


Release objects right after you add them to array - standard objective-c containers retain their elements and then release them when container itself is deallocated, so you don't need to worry about memory management yourself.

So when you create and fill your array release your elements:

Fruit * o1 = [[Fruit alloc] initWithName:kFruitOrange imageView:orange1] ;
fruitArray = [[NSMutableArray arrayWithObjects:o1, nil] retain];
[o1 release];

And in your viewDidUnload method (and in dealloc) just release your array, not its elements:

[fruitArray release];

The reason you get errors if you put [o1 release]; in your code is that in that case you release your object twice and it have been retain just once - when allocated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜