ivar を内部で使用するだけで、最新のランタイム (Snow Leopard 64 ビットおよび iOS 3.0+ だと思います) を使用している場合は、クラス拡張でプロパティを宣言し、クラス内でそれらを合成するだけです。 . ヘッダーに ivar が公開されたり、乱雑なid _internal
オブジェクトが表示されたりすることはなく、壊れやすい ivar も回避できます。
// 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+ の両方で機能することは確かです)。