例えばこんなクラスがあった時にプロパティの一覧を取得するにはどうするか?
@interface Book : NSObject {
NSString* title;
NSString* author;
NSDate* createdDate;
float weight;
}
@property (retain) NSString* title;
@property (retain) NSString* author;
@property (retain) NSDate* createdDate;
@property float weight;
@end以前紹介した StatckOverflow の記事を参考にコードを書いてみた。
How do I find all the property keys of a KVC compliant Objective-C object? - Stack Overflow
ランタイム関数 class_copyPropertyList( ) を使う。こんな感じ。
#import <objc/runtime.h>
#import "AppController.h"
#import "Book.h"
@implementation AppController
-(void)awakeFromNib
{
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([Book class], &outCount);
for(i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
const char *propType = property_getAttributes(property);
NSString *propertyName = [NSString stringWithUTF8String:propName];
NSString *propertyType = [NSString stringWithUTF8String:propType];
NSLog(@"%@: %@", propertyName, propertyType);
}
free(properties);
}
@end実行結果
2010-02-01 21:08:02.470 GetProperty[6929:10b] weight: Tf,Vweight
2010-02-01 21:08:02.475 GetProperty[6929:10b] createdDate: T@"NSDate",&,VcreatedDate
2010-02-01 21:08:02.478 GetProperty[6929:10b] author: T@"NSString",&,Vauthor
2010-02-01 21:08:02.480 GetProperty[6929:10b] title: T@"NSString",&,Vtitle
property_getAttributes の記号の意味はリファレンスに詳しく書かれている。様々な例が網羅されているの役立つ。
Mac Dev Center: Objective-C Runtime Programming Guide: Declared Properties
参考:
Mac Dev Center: Objective-C Runtime Reference - class_copyPropertyList
サンプルのソース
GitHubからどうぞ
GetProperty at master from xcatsan's SampleCode - GitHub
