【问题标题】:object not getting released in iphone对象未在 iphone 中释放
【发布时间】:2010-05-28 09:38:18
【问题描述】:
 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);

我想释放 arrRecentSearch 但它会从函数返回。我怎样才能了解这个数组。请帮助我。我正在从数据库中获取数据。

【问题讨论】:

  • return [arrRecentSearch autorelease];

标签: iphone memory-leaks


【解决方案1】:

只是自动释放它:

return [arrRecentSearch autorelease];

查看apple memopry management guidelines 了解有关其工作原理的更多信息

如果您要返回一个自动释放的对象,您必须记住保留它,以便以后保留它。即,如果我们有一个返回自动释放数组的函数

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

如果您想记住搜索结果以备后用,您必须记住这样做:

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

或者,您可以使用属性来存储它:

@property (nonatomic, copy) NSArray *searchResults;

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

不管怎样,如果你只是让它自动释放,它就会消失并且你会得到一个异常!

编辑:刚刚意识到 MustISignUp 在评论中回答了这个问题!

【讨论】:

  • 谢谢,但它会产生未捕获的异常
  • 有什么例外?获取 arrRecentSearch 的方法是否记得保留它?
  • autorelease 是返回对象的正确方法,但是调用者必须将它放在某个地方以保留它,否则它将在下次自动释放池耗尽时被释放。
  • [会话开始于 2010-05-28 19:58:25 +0530。] 2010-05-28 19:58:25.858 Handwerkersuche[1534:20b] *** 由于未捕获而终止应用程序异常“NSInvalidArgumentException”,原因:“***-[CFXPreferencesSearchListSource 计数]:无法识别的选择器发送到实例 0x4d474c0”2010-05-28 19:58:25.860 Handwerkersuche[1534:20b] 堆栈:(我收到此异常跨度>
  • 立即告诉我你没有保留它。 Objective-C 正在尝试与 NSArray 对话,但正在获取 CFXPreferencesSearchListSource 。这意味着数组已被释放,内存已用于其他用途。我已经编辑了我的答案,向您展示如何解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多