1.xib 的基本使用
- 新建 xib 文件
- 加载 xib
UIView *view = [[[NSBundle mainBundle] loadNibNamed:@"CarView" owner:nil options:nil] firstObject];
[self.view addSubview:view];
Xib 使用注意事项:
- 如果需要在Xib中添加某个View,只能在initWithCoder 中添加
- 如果子控件是从 Xib 中创建,是处于未唤醒状态,此时如果想要在某个子控件中加入View,必须得在 awakeFromNib 添加
Xib 相当于Android 中的一个View的xml布局,比如android中的recycleView 都会加载一个item_layout. 也可以把Xib 当成是stroyBorad的轻量级可视化View
2. KVC 的使用
KVC 相当于 java中的反射,可以修改类的私有成员属性
Person.m
#import "Person.h"
@implementation Person
{
int _age;
}
- (void)print{
NSLog(@"MyAge is %d",_age);
}
@end
main.m
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [[Person alloc] init];
[person setValue:@"88" forKeyPath:@"_age"];
[person print];
}
return NSApplicationMain(argc, argv);
}
3.KVC 字典转模型
字典转模型的正规操作:
Person.m:
- (instancetype)initWithDict:(NSDictionary *)dict{
if(self = [super init]){
self.money = [dict[@"money"] floatValue];
self.name = dict[@"name"];
}
return self;
}
+ (instancetype)personWithDict:(NSDictionary *)dict{
return [[self alloc]initWithDict:dict];
}
main.m:
NSDictionary *dict =@{
@"name":@"cailei",
@"money":@1888
};
Person *person = [Person personWithDict:dict];
NSLog(@"%@",person);
上面的字典转模型方式有个弊端,当你的字典中的属性非常多的时候,那么你在 Person 的构造方法中赋值语句也会越来越多。 所以可以用下面方式代替赋值语句:
[self setValuesForKeysWithDictionary:dict]
- 但是一般不用上述方法,因为上述方法中转化的必要条件是字典中的key必须在模型中找到。如果模型中带有模型,也转化不过来。
4. KVO (Key Value Observer)
KVO 相当于观察者模式,观察自身的数据的变化。先”“addObserver”“设置观察者,然后在observeValueForKeyPath 监听值的改变