如何使用@synthesize 实现保留设置器? [英] How is retain setter implemented with @synthesize?

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

问题描述

我在标题中有以下内容:

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) 创建临时变量,alloc/init(=保留),设置为属性,释放.

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 中只做了一次(例如),你可以在 dealloc 中放一个 [overlay release];.

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 实现保留设置器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆