Tom
Tom

Reputation: 4662

Memory management when to use release

I had another question about memory management in iOS 3.0+, I know if we did [varialbe release] will release its retain to an object, but code like this -

- (void) getPostsFromJson:(NSData *)data
{
    NSError *theError = nil;

    NSDictionary *dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&theError];

    if (dict == nil) {

        [SystemStatusValues getInstance].isValidJson = NO;
        [SystemStatusValues getInstance].httpStatus = HTTP_STATUS_FAILED;

        NSLog(@"getPostsFromJson - %@ %@",
              [theError localizedDescription],
              [[theError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    } else {

        NSArray *keys = [dict allKeys];        
        keys = [keys sortedArrayUsingFunction:keySortByInteger context:nil];

        self.keys = keys;
        self.posts = dict;
        NSLog(@"Posts : getPostsFromJson = %@", self.posts);

        if ([keys count] < TOTAL_SECTIONS) {

            [SystemStatusValues getInstance].isValidJson = NO;

        } else {

            [SystemStatusValues getInstance].isValidJson = YES;
            if (self.nextPosts == nil) {

            }

        }

        // [keys release];
        // [dict release];
        return;
    }
}

You can see there are two local variables - keys and dict, did I need to call [keys release] or [dict release] at the end of code? Actually I did it, but it brings crushing sometimes. So for local variables, we don't need to release it after it's used?

Upvotes: 0

Views: 109

Answers (3)

Stephen Darlington
Stephen Darlington

Reputation: 52575

It's simple:

If you alloc, copy or retain an object you need to release it. Otherwise you don’t.

So you don't need to release either keys or dict (they're both autoreleased).

Upvotes: 2

ugur
ugur

Reputation: 842

Don't release keys array. Because allKeys method probably returns autoreleased NSArray object. So it will be released later by system.

It seems like deserializeAsDictionary also returns an autoreleased NSDictionary, so you shouldn't release it too.

Release objects only created with alloc. In this case, you're using external methods. You need to follow that methods, and see if that object are created with alloc.

Upvotes: 0

0x8badf00d
0x8badf00d

Reputation: 6401

Both dict and keys are reference to autoreleased objects. You shouldn't release them, which will cause your program to terminate. You Don’t Own Objects Returned by Reference and You must not relinquish ownership of an object you do not own

So for local variables, we don't need to release it after it's used? If you own the objects you must release them when you no longer need them, doesn't matter if its local variable or ivar.

Read this - Advanced Memory Management Programming guide

Upvotes: 2

Related Questions