4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

キー値コーディング(KVC)について理解する

Posted at

キー値コーディング(KVC)とは、キー情報を用いてオブジェクトのプロパティへとアクセスする
方法のこと。

やり方は
・値を取り出すとき
[obj valueForKey:"キー名"]
・値をセットするとき
[obj setValue:"値" forKey:"キー名"]
を使う。

詳細objective-c2.0によると、
キー値コーディングの機能としては
1.キーとなる文字列は実行中に決定されてもよい。
2.プロパティへの実際のアクセス方法は利用者側から見えない
ということがあげられていた。
文字列を仲立ちとしたアクセスができるというところが
キー値コーディングの強みということかな。

※実用レベルでどう使われているか不明な点も多いので
もしご存知の方いましたらサンプルコードとか
教えて頂けると嬉しいです。

参考までに検証用に用いたコードを以下に示す。

main.m
# import <Foundation/Foundation.h>

@interface Foo : NSObject
{
    NSString* bar;
}
@property(weak,nonatomic) NSString* huga;
@property(weak,readonly,nonatomic) NSString* foobar;
@end

@implementation Foo
@synthesize huga;
@dynamic foobar;
-(NSString *)foobar
{
    return [huga stringByAppendingString:@"foobar"];
}
@end

int main()
{
    Foo *foo = [[Foo alloc] init];
    
    //普通のアクセサメソッドを使ったアクセス
    foo.huga=@"foofoo";
    NSLog(@"normal:%@",[foo huga]);
    
    //KVCによるアクセス
    [foo setValue:@"hogehoge" forKey:@"huga"];
    NSLog(@"KVC:%@",[foo valueForKey:@"huga"]);
    
    //アクセサメソッドがないインスタンス変数へのKVCでのアクセス
    [foo setValue:@"barbar" forKey:@"bar"];
    NSLog(@"アクセサメソッドなしKVC:%@",[foo valueForKey:@"bar"]);
    
    //独自定義されたアクセサメソッドへのKVCでのアクセス
    NSLog(@"original accessor method KVC:%@",[foo valueForKey:@"foobar"]);
    
    //キーとなる文字列は実行中に決定されてもよい
    NSArray *keys = @[@"huga",@"bar",@"foobar"];
    int index = arc4random() % 3;
    NSLog(@"key:%@,dynamic KVC:%@",keys[index],[foo valueForKey:keys[index]]);
    
    return 0;
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?