如果您只是在内部使用 ivar,并且您使用的是现代运行时(我认为是 Snow Leopard 64 位和 iOS 3.0+),那么您可以在类扩展中声明属性并在类中合成它们. 没有 ivars 暴露在你的标题中,没有凌乱的id _internal
对象,你也可以绕过脆弱的 ivars。
// public header
@interface MyClass : NSObject {
// no ivars
}
- (void)someMethod;
@end
// MyClass.m
@interface MyClass ()
@property (nonatomic, retain) NSString *privateString;
@end
@implementation MyClass
@synthesize privateString;
- (void)someMethod {
self.privateString = @"Hello";
NSLog(@"self.privateString = %@", self.privateString);
NSLog(@"privateString (direct variable access) = %@", privateString); // The compiler has synthesized not only the property methods, but also actually created this ivar for you. If you wanted to change the name of the ivar, do @synthesize privateString = m_privateString; or whatever your naming convention is
}
@end
除了 LLVM 之外,这还适用于 Apple 的 gcc。(我不确定这是否适用于其他平台,即不是 Apple 的 gcc,但它肯定适用于 iOS 和 Snow Leopard+)。