0

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?

2 Answers 2

2
-(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.

Sign up to request clarification or add additional context in comments.

Comments

1

Use the method in following way:

-(NSArray   *)doSomething{

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

    return  [array autorelease];

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.