synthesize实现retain

synthesize实现retain

本文介绍了如何使用@synthesize实现retain setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在标题中有以下内容:

I have the following in the header:

@property (nonatomic, retain) UIView *overlay;

并且在实施中:

@synthesize overlay;

然后:

UIView *tempOverlay = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 70.0f, 150.0f, 310.0f)];
self.overlay = tempOverlay;
[tempOverlay release];

上面不是 tempOverlay 变量?我不能这样做:

Isn't the tempOverlay variable above unnecessary? Can't I just do:

self.overlay = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 70.0f, 150.0f, 310.0f)];


推荐答案

合成的保留setter看起来像:

A synthesized retained setter looks like :

- (void)setValue: (id)newValue
{
    if (value != newValue)
    {
        [value release];
        value = newValue;
        [value retain];
    }
}

在您的情况下,您有两种有效的方法:

In your case, you have two valid methods :

1)创建一个temp var,alloc / init(=保留),设置为property,release。

1) Create a temp var, alloc/init (= retained), set to property, release.

IView *tempOverlay = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 70.0f, 150.0f, 310.0f)];
self.overlay = tempOverlay;
[tempOverlay release];

2)没有临时变量,直接设置为ivar。

2) No temp var, set directly to ivar.

overlay = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 70.0f, 150.0f, 310.0f)];

更新:
如果使用方法2),则必须明确处理其余的内存管理(不仅仅是保留),通过释放之前可能需要的任何先前值。如果只在 init 中完成一次(例如),你可以在<$中放一个 [overlay release]; c $ c> dealloc 。

UPDATE:If you use method 2), you have to explicitly handle the rest of memory management (not only retaining), by releasing any previous value it might have before if needed. If done only once in init (for instance), you can just put a [overlay release]; in dealloc.

这篇关于如何使用@synthesize实现retain setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:49