Created
October 6, 2011 13:45
-
-
Save monmon/1267428 to your computer and use it in GitHub Desktop.
privateなpropertyを作りたい時は無名カテゴリ(クラスエクステンション)を使う
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Foo.h | |
*/ | |
@interface Foo | |
// プロパティを使うのでインスタンス変数は省略する | |
// ここでは外部から触られても書き込みできないようにreadonlyにする | |
@property (readonly, retain) NSString *str; | |
@end | |
/** | |
* Foo.m | |
*/ | |
// 無名カテゴリを使ったプライベートな宣言部分 | |
@interface Foo () | |
// ここでは内部から書き込みができるようにreadwriteにする | |
@property (readwrite, retain) NSString *str; | |
@end | |
// 実装部分 | |
@implementation Foo | |
@synthesize str = _str; | |
@end |
答え
無名カテゴリを使わないとpropertyは拡張できない。
(Private)でpropertyをreadwriteを書いてもwrite権限は貰えない。
なので、propertyを拡張する(privateなpropertyを作る)時は()を使う。
privateなmethodを作る時は(Private)にする。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@interface Foo (Private)
ってやる例もあるもあるのだけど、
例えばprivateなproperty以外に
- (void)_method;
みたいなprivate methodを作ること想定した場合、
無名カテゴリなら実装しない場合にコンパイルエラーを出してくれるのでやはり無名カテゴリの方がメリットありそう。
そう考えると(Private)ってカテゴリ作るメリットは何だろう?