iOS retain count issue

92 Views Asked by At

this is part of my code:

NSMutableArray oldWordsArray;

newWordsArray= [self getNewWordArray];

-(NSMutableArray *) getOldWordArray{

    NSString *user_id = (NSString*)[tool readObkect:@"user_id"];

    NSMutableArray oldWords = [[NSMutableArray alloc]init];
    oldWords = [database getOldWord:user_id];
    NSLog(@"从所有词库中得到新单词");
    return oldWords;
}`

So: how should I release Variable oldWordsArray and oldWords, many thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

I am guessing, that you are not using ARC. This:

-(NSMutableArray *) getOldWordArray{
    NSString *user_id = (NSString*)[tool readObkect:@"user_id"];

    NSMutableArray oldWords = [[NSMutableArray alloc]init];
    oldWords = [database getOldWord:user_id];
    NSLog(@"从所有词库中得到新单词");
    return oldWords;
}

Can be translated into this:

-(NSArray *) getOldWordArray{
    NSString *user_id = (NSString*)[tool readObkect:@"user_id"];
    NSArray oldWords = [database getOldWord:user_id];
    NSLog(@"从所有词库中得到新单词");
    return oldWords;
}

And then:

- (NSArray *)oldWordArray
{
   NSString *user_id = (NSString*)[tool readObkect:@"user_id"];
   return [database getOldWord:user_id];
}

I am not sure what the database is, but it should return an autoreleased object, so you don't have to release it yourself, in that context. You should as well, not use the prefix get in getOldWord. You can as well, use an NSArray instead of a NSMutableArray.

0
On

So much discussions are here regarding this First thing You should check that if ARC enabled if yes then you don't worry about releasing it will done by ARC itself

if not then use the code like this

-(NSMutableArray *) getOldWordArray{

    NSString *user_id = (NSString*)[tool readObkect:@"user_id"];

    NSMutableArray oldWords = [[[NSMutableArray alloc]init]autorelease];
    oldWords = [database getOldWord:user_id];
    NSLog(@"从所有词库中得到新单词");
    return oldWords ;
}

or you can use

-(NSMutableArray *) getOldWordArray{

    NSString *user_id = (NSString*)[tool readObkect:@"user_id"];

    NSLog(@"从所有词库中得到新单词");
    return [database getOldWord:user_id];
}