|
|
Log In | Not a Member? |
Contact ADC |
| < 前ページ次ページ > |
Cocoaでは、オブジェクトのプロパティにアクセスする方法は主に2通りあります。すなわち、アクセサメソッドの直接呼び出しを使う静的な方法と、キー値コーディングを(KVC)を使う動的な方法です。KVCは、文字列ベースのキーを使ってプロパティを識別する汎用のプロパティアクセサメソッド、すなわちvalueForKey:とsetValue:forKey:を定義します。KVCはアクセスメソッドの使用に代わる一般的な手段として意図されているものではなく、コードがコンパイル時に当該プロパティの名前を知ることができないために選択肢が他にない場合に使います。
キー値コーディングと宣言されたプロパティは、相互に独立した技術です。プロパティを使用するかどうかに関係なくKVCを使用でき、KVCを使用するかどうかに関係なくプロパティを使用できます。どちらも「ドット構文」を使用できます。KVCの場合、構文を使ってキーパス内の要素を区切ります。ドット構文を使ってプロパティに直接アクセスするときには、レシーバ側の標準アクセサメソッドを呼び出すことを覚えておくことが重要です(当然、ドット構文ではKVCメソッドのvalueForKey:やsetValue:forKey:の呼び出しは行われません)。
たとえば、次のように定義されたクラスの場合、KVCメソッドを使ってプロパティにアクセスできます。
@interface MyClass |
@property NSString *stringProperty; |
@property NSInteger integerProperty; |
@property MyClass *linkedInstance; |
@end |
KVCを使ってインスタンス内のプロパティにアクセスできます。
MyClass *myInstance = [[MyClass alloc] init]; |
NSString *string = [myInstance valueForKey:@"stringProperty"]; |
[myInstance setValue:[NSNumber numberWithInt:2] forKey:@"integerProperty"]; |
プロパティのドット構文とKVCキーパスの違いを示すために、次の例を考えてみましょう。
MyClass *anotherInstance = [[MyClass alloc] init]; |
myInstance.linkedInstance = anotherInstance; |
myInstance.linkedInstance.integerProperty = 2; |
これは次のコードと同じ結果になります。
MyClass *anotherInstance = [[MyClass alloc] init]; |
myInstance.linkedInstance = anotherInstance; |
[myInstance setValue:[NSNumber numberWithInt:2] |
forKeyPath:@"linkedInstance.stringProperty"]; |
| < 前ページ次ページ > |
Last updated: 2007-10-31
|
Get information on Apple products.
Visit the Apple Store online or at retail locations. 1-800-MY-APPLE Copyright © 2007 Apple Inc. All rights reserved. | Terms of use | Privacy Notice |