开发者

What is the Ideal way to return data from function without leaking memory?

In IPhone Development ObjC , I wonder what is the right approach for functions to return some values in Dictionaries or Arrays. I mean should they return autorelease objects, but w开发者_JS百科ouldn't it be bad if I am using too many functions to return values, like getUserRecordsFromDB() function will return all the user records, so should they return me autorelease objects? also when I am calling them multiple times, suppose with a span of 4 seconds to get the newely updated data. Can somebody let me an ideal scanario of how to get data from a function called frequently in the flow of program, and not leaking the memory.


We should always return autorelease objects from functions and ensure they get released by setting up Autorelease pool in the calling function as follows

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// Call database function here...

[pool release];

Refer the auto release pool documentation here


If the method is in same class use global variable, if it is in some other class make sure it is allocated only one time, reuse the same memory every time it call that method.

Also check NSAutoreleasePool


Yes you should use autoreleased objects as return values.


You should stick to the cocoa programming guidelines. This is a place to start, but there is a lot more to find on the subject.


You can always pass a mutable object to be filled in.

-(void) getMoreUsers:(NSMutableArray *)ioArray {
  for ( ... ) {
    NSMutableDictionary *user = [NSMutableDictionary new];
    // fill in user ...
    [ioArray addObject:user];
    [user release]; // explicit release so only reference is owned by ioArray
  }
}

This gives you explicit control when you know the lifetime of an object, but makes it easy to write a wrapper when you want to use autorelease.

-(NSArray *) getUsers {
  NSMutableArray *result = [NSMutableArray array]; // implicit autorelease
  [self getMoreUsers:result];
  return result;
}

An example of using this with a known lifetime would be:

-(void) operateOnUsers {
  NSMutableArray *array = [NSMutableArray new];
  [self getMoreUsers:array];
  // do stuff that will not retain array
  [array release];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜