[Mac][iOS]無名カテゴリ | Cocoa練習帳

[Mac][iOS]無名カテゴリ

Objective-Cで、非公開メソッドが必要になった、無名カテゴリで実現できる。



@interface MyClass : NSObject {
}
- (void)publicMethod;
@end

@interface MyClass ()
- (void)privateMethod;
@end


カテゴリには、メソッドしか宣言できない為、無名カテゴリで非公開に出来るのはメソッドのみと考えていたが、Clang/LLVM 2.0コンパイラを使うとプロパティでもOKのようだ。



@interface MyClass : NSObject
- (void)publicMethod;
@end

@interface MyClass ()
@property (nonatomic, strong) NSMutableString *string;
- (void)privateMethod;
@end

@implementation MyClass
@synthesize string = _string;
@end


通常のクラス宣言部にも同じプロパティの宣言をして、公開用と非公開用で宣言の内容を変える事も可能なようだ。



@interface MyClass : NSObject
@property (nonatomic, strong, readonly) NSMutableString *string;
- (void)publicMethod;
@end

@interface MyClass ()
@property (nonatomic, strong, readwrite) NSMutableString *string;
- (void)privateMethod;
@end

@implementation MyClass
@synthesize string = _string;
@end


無名カテゴリは、AppleのDeveloper Libraryの説明によると、匿名のカテゴリに似ているが、正確にはクラス拡張と呼ぶ、ちょっと、異なる物のようだ。



ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/mac/anonymous_categories - GitHub

関連情報
Categories and Extensions

iOS Developer LibraryのThe Objective-C Programming Languageでの無名カテゴリの説明です。