#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
@interface score : NSObject
{
@private
NSString* scoreName;
float scoreValue;
}
-(instancetype)init;
@end
@interface person : NSObject
{
@private
NSString* name;
NSInteger age;
}
-(instancetype) initWithName:(NSString*) AName;
@end
@interface student : person
@property (retain, readwrite) NSMutableArray* ScoreInfos;
-(instancetype) initWithName:(NSString*) AName;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*valueforkey*/
person* p = [[person alloc] initWithName:@"hello"];
NSLog(@"%@",[p valueForKey:@"name"]);
NSString* sValue = @"world";
NSError* err = nil;
if ([p validateValue:&sValue forKey:@"name1" error:&err]) {
[p setValue:@"world" forKey:@"name"];
NSLog(@"%@",[p valueForKey:@"name"]);
}
score* c1 = [[score alloc] init];
[c1 setValue:@"数学" forKey:@"scoreName"];
[c1 setValue:@"94" forKey:@"scoreValue"];
score* c2 = [[score alloc] init];
[c2 setValue:@"语文" forKey:@"scoreName"];
[c2 setValue:@"90" forKey:@"scoreValue"];
score* c3 = [[score alloc] init];
[c3 setValue:@"英语" forKey:@"scoreName"];
[c3 setValue:@"88" forKey:@"scoreValue"];
student* s = [[student alloc]initWithName:@"xiaoming"];
[s.ScoreInfos addObject:c1];
[s.ScoreInfos addObject:c2];
[s.ScoreInfos addObject:c3];
NSLog(@"共%@门课.最高分:%f,最低分:%f,平均分:%f,总分:%f",
[s valueForKeyPath:@"ScoreInfos.@count"],
[[s valueForKeyPath:@"ScoreInfos.@max.scoreValue"] floatValue],
[[s valueForKeyPath:@"ScoreInfos.@min.scoreValue"] floatValue],
[[s valueForKeyPath:@"ScoreInfos.@avg.scoreValue"] floatValue],
[[s valueForKeyPath:@"ScoreInfos.@sum.scoreValue"] floatValue]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
@implementation person
-(BOOL)validateValue:(inout __autoreleasing id *)ioValue forKey:(NSString *)inKey error:(out NSError *__autoreleasing *)outError
{
return [inKey isEqualToString:@"name1"]?NO:YES;
}
-(instancetype)init
{
if (self = [super init]) {
name = @"no name";
}
return self;
}
-(instancetype)initWithName:(NSString *)AName
{
if (self = [super init]) {
name = AName;
}
return self;
}
@end
@implementation score
/*在类中如果不定义它,就不能调用,不清楚原因~*/
-(instancetype)init
{
if (self = [super init]) {
return self;
}
return self;
}
@end
@implementation student
-(instancetype)initWithName:(NSString *)AName
{
if (self = [super initWithName:AName]) {
self.ScoreInfos = [[NSMutableArray alloc] initWithCapacity:3];
}
return self;
}
@end
完全利用了运行时类型信息rtti的特性,查找的方式没有研究,可参考http://www.cnblogs.com/jy578154186/archive/2013/02/27/2935413.html