Retain Count Question: Some Guidance, Please

谁说我不能喝 提交于 2019-12-08 10:17:33

问题


[I'm sure this is not odd at all, but I need just a bit of help]

I have two retain properties

@property (nonatomic, retain) NSArray *listContent;
@property (nonatomic, retain) NSArray *filteredListContent;

and in the viewDidLoad method I set the second equal to the first (so now the retainCount is two, I think):

self.filteredListContent = self.listContent;

and then on every search I do this

 self.filteredListContent  = [listContent filteredArrayUsingPredicate:predicate];

I thought I should do a release right above this assignment -- since the property should cause an extra retain, right? -- but that causes the program to explode the second time I run the search method. The retain counts (without the extra release) are 2 the first time I come into the search method, and 1 each subsequent time (which is what I expected, unfortunately).

Some guidance would help, thanks! Is it correct to not release?


回答1:


You don't have to release it, that's correct.

Because the variable is stored in two locations, its retain count should be 2. Here's the reason it crashes. (Retain count of self.listContent in brackets.)

self.listContent = someArray                [1]
self.filteredListContent = self.listContent [2]
[self.filteredListContent release]          [1]

self.filteredListContent = somethingElse    [0] -> deallocation of listContent
[self.listContent doSomething]              [whoops, bad things happen]

self.listContent gets deallocated too early. If you don't use [... release]it the retain count math works.

Read Vincent Gable's blog for a really short summary on when to use release. (Interestingly, this blog post was inspired by Andiih's answer on Stackoverflow.)




回答2:


No, you do not need to make a retain call prior to running the filter search. Any old value in the property will be released.

The first time you check the retain count, self.filteredListContent and self.listContent reference the same array object and both have a reference counter for that array. After the search self.listContent's retain count drops to 1 because it was released by self.filteredListContent when the search results were set (and subsequently retained).




回答3:


If you didn't NARC* the object, you don't need to release it.

*NARC -- New, Alloc, Retain, Copy

A retained property both retains the new value on assignment and releases the old value when that happens.



来源:https://stackoverflow.com/questions/2907992/retain-count-question-some-guidance-please

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!