在 C# 里我们常用 .net reflect 类库配合typeof/getType来反射设置函数与字段等等。在iOS里也有这样的功能,比C#的门槛低的多。只要你合乎规范的定义函数与属性字段,就能方便的使用。
使用KVC
下面的函数 我将接通过KVC的接口 setValue forKey && setValue forKeyPath ,来设置属性 与 调用方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #import <Foundation/Foundation.h> #import "Foo.h" #import "Bar.h"
int main(int argc, const char * argv[]) { Foo* foo = [[Foo alloc]init]; foo.bar = [[Bar alloc]init];
[foo setValue:@"blah blah" forKey:@"stringOnFoo"]; [foo setValue:@"testforkeyle" forKeyPath:@"bar.stringOnBar"]; [foo valueForKeyPath:@"Log"]; NSLog(@"%@",foo.bar.stringOnBar); NSLog(@"%@",foo.stringOnFoo); return 0; }
|
使用KVC在便利数组上尤为方便,下面是使用@sum函数直接给数组的price属性求和。
1
| [foo.bar.array valueForKeyPath:@"@sum.price"];
|
KVC的其他函数
1 2 3 4 5 6 7 8 9
| @avg @count @max @min @sum @unionOfArrays/@distinctUnionOfArrays @unionOfSets/@distinctUnionOfSets @unionOfObjects/@distinctUnionOfObjects
|
使用要求
- 骆驼命名法,不能数字开头
- 不能包含空格
- 键必须是ASCII编码的
- 使用默认的get/set