15

在实现接口时,教程和文献中的常用方法似乎是声明一个 ivar,然后设置@propertythen @synthesize

@interface MyClass : NSObject {
NSString *myString;
}

@property (nonatomic, retain) NSString *myString;
@end

但是,省略显式声明并仅放置 @property 具有相同的效果。

@interface MyClass: NSObject {
}

@property (nonatomic, retain) NSString *myString;
@end

那么为什么大多数人都使用@property和显式声明呢?不这样做是不好的形式吗?

4

4 回答 4

15

曾经是必须的。Objective-C 运行时有两个不同的版本:一个仅 32 位的“遗留”运行时(旧版本)和一个 32/64 位运行时(新的 32 位运行时仅用于 iOS 设备和iOS 模拟器)。

我认为唯一仍然需要这样做的地方是当您以 32 位模式(10.5 或 10.6)运行应用程序时。其他任何地方(64 位 Leopard、64 位 Snow Leopard、Lion、iOS)都使用具有“自动 ivar 合成”的更新运行时,并且生成的 ivars 被称为“合成 ivars”。

于 2011-04-05T17:27:20.297 回答
2

有些平台支持合成实例变量,有些不支持。显式声明实例变量使您的代码在更多地方有效,并且直到最近它一直是完全必要的,所以人们仍然这样做。几年后,他们可能不会了。

于 2011-04-05T17:26:01.200 回答
1

Using modern versions of Xcode (anything about 4.2 or later) there is no reason to declare a iVar in your header, EVER. Anything publicly accessible should be declared as a property.

Many forget that Objective C objects are actually pointers to C structs. As such, any iVar that is declared in your header can be accessed directly, by passing your getters and setters, using myObject->myPublicIVar. Especially in non-ARC code, that is extremely dangerous. The @private directive prevents the use the -> operator to access iVars, but still clutters the header file. There's no point in @private when there are better ways.

Anything private should be declared within your .m file. Often, this requires a class extension, like this:

// The .h file
@interface Foo : NSObject
@property (nonatomic, strong) NSString *myPublicString;
@end


// The .m file
@interface Foo ()
@property (nonatomic, strong) NSString *myPrivateString;
@end

@implementation Foo {
    NSString *myPrivateIVar;
}

// Xcode 4.5 or later will not require these @synthesize
@synthesize myPublicString = _myPublicString;
@synthesize myPrivateString = _myPrivateString;

@end

An implementation like this provides a public property backed by an iVar, a private property backed by an iVar, and a private independent iVar. I've included the @synthesize directives, but they are not necessary using modern tools.

于 2013-10-19T19:22:57.727 回答
-3

@property 仅实现访问器方法,实例变量本身必须存在。尝试忽略 ivars,它会在运行时失败,如果不是在编译时。

于 2011-04-05T17:17:20.307 回答