OC-9.22
1.KVC/KVO
課前小菜:
如何判斷數組中是否有哪個值,只需要遍歷一遍然后進行賦值,將數組中的每個值變為數字.(哈希算法思想)
array[42] = 1
array[29] = 1
... ...
--->number
1.1 KVC:(批量賦值)繼承 NSKeyValueCoding協議,
設置
setValue: forkey:(實例變量,屬性)查找
valueForKey設置
setValue: forkeyPath:查找
valueForKeyPath:
1.1.1三種情況下,程序會崩潰。解決方案:重寫其方法。
- 當使用KVC對非對象值類型進行賦值nil的時候
[animal setValue:nil forKey:@"age"];
- (void)setNilValueForKey:(NSString *)key{
[self setValue:@0 forKey:key];
NSLog(@"-------nil---:%@",key);
}
- 當使用KVC機制,valueForKey找不到key的時候
NSString *value = [animal valueForKey:@"hello"];
- (id)valueForUndefinedKey:(NSString *)key{
return key;
}
- 當使用KVC機制,對key賦值的時候,沒有這個key
[animal setValue:dog forKey:@"dog"];
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
NSLog(@"---undefKey:%@",key);
}
1.2 KVO:基于KVC機制,在底層使用了KVC機制,觀察者
1.2.1三步走
- 添加觀察
[_animal addObserver:self forKeyPath:@"height" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
- 實現
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"keyPath:%@",keyPath);
NSLog(@"change:%@",change);
NSLog(@"--value:%@",change[@"new"]);
}
- 移除觀察
- (void)dealloc{
[_animal removeObserver:self forKeyPath:@"height"];
}
2.解歸檔:
NSKeyedArchiver/NSKeyedUnArchiver
首先在聲明文件中定義兩個屬性(name,age)
實現如下:
#import "ViewController.h"
//繼承協議(NSCoding)
@interface ViewController ()<NSCoding>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ViewController *view1;
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/1.plist"];
//判斷路徑下是否已有文件,沒有就寫入
if (![NSKeyedUnarchiver unarchiveObjectWithFile:path]){
ViewController *view = [ViewController new];
view.name = @"stone";
view.age = 12;
//歸檔
[NSKeyedArchiver archiveRootObject:view toFile:path];
}
//讀取文件,存進去是對象取出來也是對象,解歸檔
view1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"path = %@",path);
NSLog(@"view.name = %@",view1.name);
}
//實現NSCoding協議中的倆個方法
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]){
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
@end
3. 數組:
- 默認的數組是不可變的,
3.1 將不可變數組變為可變數組的方法:
1.array.mutableCopy
2.NSMutable
- 可變和非可變的數組經過copy后都是不可變的,
不可變的--->不可變的,所以兩個數組都是同一個地址,為同一個(因為創建一個新的,不可變的沒有意義)。
可變的--->不可變的,兩個數組不是同一個地址。
- 可變和非可變的數組經過mutable后都是可變的,
不可變的--->可變的,
可變的--->可變的,
兩個數組不是同一個地址。創建了一個新的對象,為不同的地址