开发者

newbie question on iOs memory management

开发者 https://www.devze.com 2023-03-26 06:11 出处:网络
How to write right in this situation: I have some method, that return NSMutableArray*. Because method not started with init, new or alloc, how write in apple memory-management guide, i return autorea

How to write right in this situation:

I have some method, that return NSMutableArray*. Because method not started with init, new or alloc, how write in apple memory-management guide, i return autorealese object.

-(NSMutableArray*)someMethod {

    NSMutableArray *array = [NSMutableArray alloc] init] autorealese];
    //Some code here
    return array;
}

And i have some another methods, that call this one:

-(NSMutableArray*)method1 {
     NSMutableArray *array = nil;
     if(condition){
         array = [self someMethod];
     }
     return array;
}

-(NSMutableArray*)method2 {
     NSMutableArray *array = nil;
     array = [self method1];
}

Code work.But XCode analyze tool says that in method2 i get object w开发者_如何转开发ith count 0. So, how to write this code good?


There is nothing wrong with your code, except that the method2 will return the array that is autoreleased. Thus whatever is calling this method should retain the return value.


Creating an autoreleased NSMutableArray and returning it.

-(NSMutableArray*)someMethod {

        NSMutableArray *array = [NSMutableArray alloc] init] autorealese];
        //Some code here
        return array;
    }

Method1 uses autorelease NSMutableArray from someMethod and for the life of Method1 the array will not be autoreleased. That's one of the rules of memory management in objective-c that object lives through the method cycle.

-(NSMutableArray*)method1 {
     NSMutableArray *array = nil;
     if(condition){
         array = [self someMethod];
     }
     return array;
}

Method2 uses still waiting to be autoreleased NSMutableArray from method1. It's important to notice that b/c you have a condition in method2 the array might be nil.

-(NSMutableArray*)method2 {
     NSMutableArray *array = nil;
     array = [self method1];
}

So in another words, you are passing autoreleased object along your methods. There is nothing wrong with this. You just have to remember that if you want to store the value of method2 you need to retain it, or it will get autoreleased.

Because of your condition in method1 the analyzer will complain b/c it's not guaranteed that the method1 will return an object, there is a possibility it will return nil.

0

精彩评论

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