asedra_le
asedra_le

Reputation: 3067

Problem with memory manament in Objective-C

I have a method:

-(NSArray   *)doSomething{

    NSArray *array = [[NSArray alloc] initWithObjects:@"Huy 1",@"Huy 2",@"Huy 3",nil];

    [array  release];

    return  array;

}

and

- (void)viewDidLoad {

    [super viewDidLoad];

    NSArray *array  =   [self   doSomething];

    if(array&&array.count>0){

        NSLog([NSString stringWithFormat:@"%@\n",[array objectAtIndex:1]]);

    }
    else{

        NSLog(@"Null");

    }

}

I thinks i released array on doSomething() so it won't return NSArray which i created on doSomething(). I don't know it still print "Huy 2"? Anybody can tell me why?

Upvotes: 0

Views: 77

Answers (2)

Benedict Cohen
Benedict Cohen

Reputation: 11920

-(NSArray *)doSomething
{
    NSArray *array = [[NSArray alloc] initWithObjects:@"Huy 1",@"Huy 2",@"Huy 3",nil];

    return  [array autorelease];
}

Memory Management Programming Guide

- (void)viewDidLoad 
{
    [super viewDidLoad];
    NSArray *array  =   [self doSomething];

    if([array count]) //if array is nil this will evaluate to false. If count is 0 this will evaluate to false too.
    {
        NSLog(@"%@\n", [array objectAtIndex:1]); //NSLog insert values for you
    }
    else
    {
        NSLog(@"Null");
    }
}

If this works with release instead of autorelease it's probably because the memory that the array was using has yet to be used by anything else. This is just chance. I suspect that if you allocate an object after NSArray *array = [self doSomething]; you will get unexpected results.

Upvotes: 2

Sagar
Sagar

Reputation: 3149

Use the method in following way:

-(NSArray   *)doSomething{

    NSArray *array = [[NSArray alloc] initWithObjects:@"Huy 1",@"Huy 2",@"Huy 3",nil];

    return  [array autorelease];

}

Upvotes: 1

Related Questions