KVC = Key Value Coding
@interface Member : NSObjext{
NSString *name;
NSString *addr;
NSString *tel;
NSInteger *wallet;
}
read方法
NSString *name = [member valueForKey:@"name"];
若Application有物件
NSString *name = [application valueForKeyPath:@"member.name"];
set方法
[member setValue:@"bob" forKey:@"name"];
[application setValue:@"bob" forKey:@"member.name"];
NSDictionary
read
@interface Member : NSObjext{
NSString *name;
NSString *addr;
NSString *tel;
NSInteger wallet;
}
@property (nonatomic,retain) NSString *name;
@property (nonatomic,retain) NSString *addr;
@property (nonatomic,retain) NSString *tel;
@property (nonatomic,retain) NSString wallet;
@implementation Member
@synthesize name,addr,tel,wallet;
@end
NSDictionary *
read
NSDictionary *properties = [self dictionaryWithValuesForKeys:[NSArray arrayWithObjects:@"name",@"addr",@"tel",@"wallet",nil];
未知的key值 valueForUndefinedKey:
硬找會發生NSUndefinedKeyException
NSDictionary中
NSInteger會被轉成->NSNumber
nil會被轉成->NSNull
set方法
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:@"bob",@"name",@"addr",@"綠島",@"0912345678", [NSNumber numberWithInt:30000],@"wallet",nil]; [self setValuesForKeyWithDictionary:properties];
動態取得屬性名稱
在NSObject加入方法
#import@interface NSObject(Private) +(NSArray *)propertyName; @end @implementation NSObject (Private) +(NSArray *)propertyNames{ unsigned int cnt,i; objc_property_t *properties = class_copyPropertyList([self class],&cnt); NSMutalbeArray *propNames = [NSMutableArray arrayWithCapacity:cnt]; for(i = 0 ; i < cnt ; i++){ objc_property_t property = properties[i]; const char *propName = property_gerName(property); NSString *propertyName = [NSString stringWithUTF8String:propName]; [propNames addObject:propertyName]; } free(properties) return propNames; } @end NSDictionary *properties = [self dictionaryWithValuesForKeys:[User propertyNames]];
KVO = Key Value Observers
沒有留言:
張貼留言