9.23 - OC - KVC/KVO Array

2016-09-23  本文已影响42人  没有北方的南方

OC-9.22

1.KVC/KVO

课前小菜:

如何判断数组中是否有哪个值,只需要遍历一遍然后进行赋值,将数组中的每个值变为数字.(哈希算法思想)

array[42] = 1

array[29] = 1

... ...

--->number

1.1 KVC:(批量赋值)继承 NSKeyValueCoding协议,

1.1.1三种情况下,程序会崩溃。解决方案:重写其方法。

[animal setValue:nil forKey:@"age"];

- (void)setNilValueForKey:(NSString *)key{

    [self setValue:@0 forKey:key];
    NSLog(@"-------nil---:%@",key);
}

NSString *value = [animal valueForKey:@"hello"];

- (id)valueForUndefinedKey:(NSString *)key{

    return 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

不可变的--->不可变的,所以两个数组都是同一个地址,为同一个(因为创建一个新的,不可变的没有意义)。

可变的--->不可变的,两个数组不是同一个地址。

不可变的--->可变的,

可变的--->可变的,

两个数组不是同一个地址。创建了一个新的对象,为不同的地址

上一篇下一篇

猜你喜欢

热点阅读