#import <Foundation/Foundation.h>
@interface PlayItem : NSObject{
NSString *name;
float price;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) float price;
@end
#import "PlayItem.h"
@implementation PlayItem
@synthesize name = _name;
@synthesize price = _price;
- (void)dealloc
{
self.name = nil;
[super dealloc];
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
NSLog(@"function %@ is calling", NSStringFromSelector(_cmd));
}
@end
#import <Foundation/Foundation.h>
#import "PlayItem.h"
@interface PlayList : NSObject{
float number;
NSString *name;
NSMutableArray *itemlist;
PlayItem *currItem;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSMutableArray *itemlist;
@property (nonatomic, retain) PlayItem *currItem;
@property (nonatomic, assign) float number;
@end
#import "PlayList.h"
@implementation PlayList
@synthesize number = _number, name = _name, currItem = _currItem,
itemlist = _itemlist;
- (id)init
{
self = [super init];
if (self){
self.currItem = [[[PlayItem alloc]init] autorelease];
self.itemlist = [NSMutableArray array];
for (int i = 0; i < 20; i ++){
PlayItem *pi = [[PlayItem alloc]init];
pi.name = [NSString stringWithFormat:@"name %d", i];
pi.price = 100 + i;
[self.itemlist addObject:pi];
[pi release];
}
}
return self;
}
- (void)dealloc
{
self.name = nil;
self.currItem = nil;
self.itemlist = nil;
[super dealloc];
}
@end
//测试
//kvc
PlayList *pl = [[PlayList alloc]init];
[pl setValue:@"lan" forKey:@"name"];
NSLog(@"name is %@", pl.name);
id v = [pl valueForKey:@"number"];
NSLog(@"v is %@", v);
//设置多级
[pl setValue:@"current " forKeyPath:@"currItem.name"];
NSLog(@"%@", pl.currItem.name);
//设置一批
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"200", @"number",
@"lan", @"name", nil];
[pl setValuesForKeysWithDictionary:dict];
NSLog(@"%@, %f", pl.name, pl.number);
//取出值
id obj = [pl valueForKey:@"itemlist"];
NSLog(@"%@", obj);
//取出多级
id obj2 = [pl valueForKeyPath:@"itemlist.name"];
NSLog(@"%@", obj2);
//使用kvo内置属性fangfa
NSLog(@"sum %@", [pl.itemlist valueForKeyPath:@"@sum.price"]);
NSLog(@"avg %@", [pl.itemlist valueForKeyPath:@"@avg.price"]);
NSLog(@"max %@", [pl.itemlist valueForKeyPath:@"@max.price"]);
NSLog(@"min %@", [pl.itemlist valueForKeyPath:@"@min.price"]);
objective-c kvo
最新推荐文章于 2018-07-05 22:06:00 发布