gpt4 book ai didi

objective-c - 如何释放保留对象的内存

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:50:24 25 4
gpt4 key购买 nike

这是我的一种方法。

- (void)getSearchResultsByKeyword:(NSString *)keyword 
searchOptions:(NSArray *)searchOptions
searchGroupsInResult:(NSArray *)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];
}

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

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

打电话。 ([关键字发布][_searchKeyword 发布])??

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

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

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

我正在研究 XCode4 和 iOS 4.3。

谢谢。

最佳答案

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

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

@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com