Objective-C,带属性的接口声明 [英] Objective-C, interface declarations with properties

查看:118
本文介绍了Objective-C,带属性的接口声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下常见示例中,

////
@interface MyObject : NSObject
{
 @public
  NSString * myString_;
}

@property (assign) NSString * myString;
@end

@implementation MyObject
@synthesize myString = myString_;
@end
////

为什么声明 myString _ ?

我问,因为我们仍然可以获取并设置 myString 在实现中使用 self.myString [self myString] self。 myString = ... [self setMyString:...] 事实上我们必须保留它。

I ask because we can still get and set myString in the implementation using self.myString, [self myString], self.myString = ... and [self setMyString:...] and in fact we must if instead it's being retained.

推荐答案

使用现代的Obj-C运行时,声明ivar比其他任何东西都更具形式。但是,有一些内存管理要记住。

With the modern Obj-C runtime, declaring the ivar is more of a formality than anything else. However, there are some memory management things to keep in mind.

首先,对象类型的属性声明通常是 retain ,或者字符串可能是 copy 。在任何一种情况下,都会保留新对象。

First, the property declaration for an object type is usually retain, or for strings it may be copy. In either case, the new object is retained.

给出以下代码:

NSString *string = [[NSString alloc] init];
myString_ = string;
self.myString = string;    // If the property was retain or copy

第二项任务将泄漏;第一个不会。这是因为该属性将保留已保留计数为1的内容 - 现在为2.当您在 dealloc 中释放该属性时,计数将变为1,不是0,所以它不会被释放。但是,使用第一个选项时,保留计数保持为1,因此 dealloc 将其降至0。

The second assignment would leak; the first would not. This is because the property would retain something that already has a retain count of 1—it is now at 2. When you release the property in dealloc, the count goes to 1, not 0, so it won't be released. With the first option, however, the retain count stays at 1, so dealloc brings it down to 0.

在您的示例中,将该属性保留为 assign 将使ivar声明成为正式。

In your example, leaving the property as assign will make the ivar declaration a formality.

这篇关于Objective-C,带属性的接口声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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