OGeek|极客世界-中国程序员成长平台

标题: objective-c - 如何释放保留对象的内存 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 20:04
标题: objective-c - 如何释放保留对象的内存

这是我的方法之一。

- (void)getSearchResultsByKeywordNSString *)keyword 
                searchOptionsNSArray *)searchOptions 
         searchGroupsInResultNSArray *)searchGroupsInResult
{
    _searchKeyword = [keyword retain];
    _searchOptions = [searchOptions retain];
    _searchGroupsInResult = [searchGroupsInResult retain];
    [_searchResultsGroups removeAllObjects];
    [_searchResultsGroupsIndexToNameMap removeAllObjects];
    _pageNo = 1;
    [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:SearchResultsRetrievingStartLodingNotification 
                                                                object:self];
    [_dataProvider startGettingSearchResultsByKeyword:self.searchKeyword 
                                    searchOptions:_searchOptions
                             searchGroupsInResult:_searchGroupsInResult
                                           pageNo:_pageNo
                                         delegate:self];
}

在我的方法中,我对作为参数的对象调用了保留。所以我拥有该对象并增加了保留计数。所以我的问题是,如何在

之后减少保留计数
[_dataProvider startGettingSearchResultsByKeyword:self.searchKeyword 
                                        searchOptions:_searchOptions
                                 searchGroupsInResult:_searchGroupsInResult
                                               pageNo:_pageNo
                                             delegate:self];

打电话。 ( [keyword release][_searchKeyword release] ) ??

在我的头文件中,我已将 _searchOptions 声明为私有(private)实例,并将 _searchKeyword 声明为 readonly 属性。在我的实现文件中,我在 dealloc 中发布了这两个实例。

我运行了分析工具,但它没有将这件事显示为问题。但我对此表示怀疑。

所以,请告诉我处理这件事的必要方法。

我正在开发 XCode4 和 iOS 4.3。

谢谢。



Best Answer-推荐答案


jaydee3 的回答是正确的。我要补充一点,您真的 应该将@properties 与合成访问器一起使用。然后,不要直接设置实例变量,而是使用访问器方法。这样,您可以将实例变量的所有内存管理封装在访问器方法中。这样做的好处是更具可读性,更不容易出错,并且使您的代码在将来更容易修改。

因此,在您的 .h 中(如果属性应该是“私有(private)”,则在您的 .m 中的类扩展中):

@property (nonatomic, copy) NSString *searchKeyword;

在你的 .m 中:

- (void)dealloc
{
    self.searchKeyword = nil;

    [super dealloc];
}

@synthesize searchKeyword = _searchKeyword;

最后,在你的 -getSearchResultsByKeyword:searchOptions:searchGroupsInResult: 方法中:

self.searchKeyword = keyword;

而不是

_searchKeyword = [keyword retain];

现在您不必担心释放保留searchKeyword。 @synthesize 指令生成的 setter 方法将为您处理它。我建议阅读 Apple 关于 Declared Properties 的文档.

关于objective-c - 如何释放保留对象的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9927127/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4