object not getting released in iphone

2019-09-16 06:04发布

问题:

 NSString *strSql = @"select tblrecentsearch_id,xmlrequest,company,postcode,city,kilometer,date from tblrecentsearch";

 returnValue = sqlite3_prepare_v2(database, [strSql UTF8String], -1, &selectStatement, NULL);
 if(returnValue == SQLITE_OK)
 {
  arrRecentSearch=[[NSMutableArray alloc] init];

  while(sqlite3_step(selectStatement)==SQLITE_ROW)
  {
   Search *ObjSearch = [[Search alloc]init];
   ObjSearch.intRecentSearchId = sqlite3_column_int(selectStatement, 0);
   ObjSearch.xmlRequest = [NSString stringWithCString:(char  *)sqlite3_column_text_check(selectStatement, 1) encoding:NSUTF8StringEncoding];
   ObjSearch.strCompnay=[NSString stringWithCString:(char  *)sqlite3_column_text_check(selectStatement, 2) encoding:NSUTF8StringEncoding];
   ObjSearch.strPostCode=[NSString stringWithCString:(char  *)sqlite3_column_text_check(selectStatement, 3) encoding:NSUTF8StringEncoding];
   ObjSearch.strPlace = [NSString stringWithCString:(char  *)sqlite3_column_text_check(selectStatement, 4) encoding:NSUTF8StringEncoding];
   ObjSearch.strKilometer = [NSString stringWithCString:(char  *)sqlite3_column_text_check(selectStatement, 5) encoding:NSUTF8StringEncoding];
   ObjSearch.strDate = [NSString stringWithCString:(char  *)sqlite3_column_text_check(selectStatement, 6) encoding:NSUTF8StringEncoding];

   [arrRecentSearch addObject:ObjSearch];

   [ObjSearch release];
  }
 }

 sqlite3_finalize(selectStatement);

I want release arrRecentSearch but it will return from function . How can i realese this array. Please help me.I am fetching data from databse.

回答1:

just autorelease it :

return [arrRecentSearch autorelease];

Have a look at the apple memopry management guidelines for more information on how this works

If you are going to return an autoreleased object, you must remember to retain it if you wnat to keep it around later. i.e. if we have a function that returns an autoreleased array

- (NSArray *) getSearchResults {
    return [[[NSArray alloc] init] autorelease];
}

and you want to remember the search results for later you must remember to do this :

...
NSArray *results = [[self getSearchResults] retain]; //!< Remember the retain here!
...

or, you might use a property to store it :

@property (nonatomic, copy) NSArray *searchResults;

...
self.searchResults = [self getSearchResults]; //!< The property handles the retain for you here
...

Either way, if you just leave it as autoreleased, it's going to vanish and you're going to get an exception!

EDIT: Just realised MustISignUp has answered this in a comment!