objective-c - @synthesize variable = t_variable 到底有什么作用?是不是很有帮助?

标签 objective-c ios

我知道 @synthesize -ing 变量会自动为我的 .h 文件中定义的 @property 创建访问器方法,并使用 = _variable 告诉编译器用于我的支持变量的名称,但它对我还有其他作用吗? 我几乎一直在使用类似的东西来分配和读取我的类变量

self.variableName = somethingElse

self.someLabel.text = self.someString

我可以(假设所有@synthesize语句都是正确的,等等)做类似的事情吗?

_variableName = somethingElse

我可以使用 _variable 而不是使用 self.variable 而不用担心吗?我应该在 dealloc 中使用 [_variablerelease] 还是 [self.variablerelease]

我仍然对 Objective-C/cocoa/iOS 开发的一些原因感到困惑。

最佳答案

@synthesize varible1 相当于 @synthesize variable1 = variable1 -- 这表示您为实例变量和属性指定了相同的名称。

当您说@synthesizevariable1=variable2时,variable1是属性的名称,variable2是实例变量的名称。

使用上面的@synthesize语句,如果你说:

self.variable1 = something; 

然后,如果该属性具有“retain”属性,则对象 something 会被保留(并且variable1 中的任何旧对象都会被释放)。

但是如果你说:

variable2 = something;

然后不会发生保留/释放。这很可能会导致丢失对象错误。

至于dealloc中的释放,你可以说:

[self.variable1 release];

[variable2 release];

尽管后者是首选。

你也可以说:

self.variable1 = nil;

这将释放变量并将其归零。

但请注意,前两种形式应该dealloc中使用。

关于objective-c - @synthesize variable = t_variable 到底有什么作用?是不是很有帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9090764/

相关文章:

ios - 在 Swift 中的 presentViewController 之后调用 pushViewController

ios - 如何在 objective-c 中从谷歌驱动器下载jpg、png、pdf、doc.ppt、rtf等文件

ios - 在Splitviewcontroller中从左到右更改Masterview的位置

ios - 如何获取 UIImage 中指定颜色的位置?

objective-c - 如何使 NSView 透明并显示 NSWindow 下的内容?

objective-c - 使用 valueForKeyPath 获取 NSImageView 子类数组的最小 x 和 y 原点

ios - 将背景图片设置为 iPad 应用程序的正确方法

ios - NSTimer 在后台不工作

ios - 万向节示例项目 (Mallmart) 架构 armv7 的 undefined symbol :

ios - 使用hpple从html中获取表格数据