iOS_技巧(11) _KVO_手动发送通知

一丶KVO Compliance 原始文档

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVOCompliance.html

二丶发送通知使用介绍:

2.1自动发送通知;

   ######2.1.1 set方法
    // Call the accessor method.
    [account setName:@"Savings"];
    ######2.1.2 kvc
    // Use setValue:forKey:.
    [account setValue:@"Savings" forKey:@"name"];

  ######2.1.3 kvc 路径法
    // Use a key path, where 'account' is a kvc-compliant property of 'document'.
    [document setValue:@"Savings" forKeyPath:@"account.name"];

  ######2.1.3 kvc 获取一个数组
    // Use mutableArrayValueForKey: to retrieve a relationship proxy object.
    Transaction *newTransaction = <#Create a new transaction for the account#>;
    NSMutableArray *transactions = [account mutableArrayValueForKey:@"transactions"];
    [transactions addObject:newTransaction];

2.2 手动发送通知

2.2.1控制
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key
{

    if ([key isEqualToString:@"想要手动控制的key"])return NO;

    return [super automaticallyNotifiesObserversForKey:key];
}
2.2.2 手动发送
重写set方法;
- (void)setTmpStr:(NSString *)tmpStr
{
    [self willChangeValueForKey:@"tmpStr"];

    _tmpStr = tmpStr;

    [self didChangeValueForKey:@"tmpStr"];
}
2.2.3 提升性能的手动发送
- (void)setTmpStr:(NSString *)tmpStr
{
    if (![_tmpStr isEqualToString:tmpStr])
    {
        [self willChangeValueForKey:@"tmpStr"];

        _tmpStr = tmpStr;

        [self didChangeValueForKey:@"tmpStr"];
    }
}

2.2.4 实现一个key修改,多个key同时修改

- (void)setTmpStr:(NSString *)tmpStr
{
    if (![_tmpStr isEqualToString:tmpStr])
    {
        [self willChangeValueForKey:@"tmpStr"];
        [self willChangeValueForKey:@"修改发送的通知1号Key"];
        [self willChangeValueForKey:@"修改发送的通知2号Key"];
        _tmpStr = tmpStr;

        [self didChangeValueForKey:@"tmpStr"];
        [self didChangeValueForKey:@"修改发送的通知1号Key"];
        [self didChangeValueForKey:@"修改发送的通知2号Key"];
    }
}
2.2.5 最后一个,没用过,简单介绍
typedef enum NSKeyValueChange : NSUInteger {
    NSKeyValueChangeSetting = 1,
    NSKeyValueChangeInsertion = 2,
    NSKeyValueChangeRemoval = 3,
    NSKeyValueChangeReplacement = 4
} NSKeyValueChange;

移除 Transactions 中元素时手动触发 KVO 例子:

- (void)removeTransactionsAtIndexes:(NSIndexSet *)indexes
{

    [self willChange:NSKeyValueChangeRemoval valuesAtIndexes:indexes forKey:@"transactions"];

    // Remove the transaction objects at the specified indexes.

    [self didChange:NSKeyValueChangeRemoval valuesAtIndexes:indexes forKey:@"transactions"];
}
IT文库 » iOS_技巧(11) _KVO_手动发送通知
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址