iOS下KVO使用過(guò)程中的陷阱KVO,

【原】iOS下KVO使用過(guò)程中的陷阱KVO,全稱(chēng)為Key-Value Observing,是iOS中的一種設(shè)計(jì)模式,用于檢測(cè)對(duì)象的某些屬性的實(shí)時(shí)變化情況并作出響應(yīng)。網(wǎng)上廣為流傳普及的一個(gè)例子是利用KVO檢測(cè)股票價(jià)格的變動(dòng),例如這里。這個(gè)例子作為掃盲入門(mén)還是可以的,但是當(dāng)應(yīng)用場(chǎng)景比較復(fù)雜時(shí),里面的一些細(xì)節(jié)還是需要改進(jìn)的,里面有多個(gè)地方存在crash的危險(xiǎn)。本文旨在逐步遞進(jìn)深入地探討出一種目前比較健壯穩(wěn)定的KVO實(shí)現(xiàn)方案,彌補(bǔ)網(wǎng)上大部分教程的不足!首先,假設(shè)我們的目標(biāo)是在一個(gè)UITableViewController內(nèi)對(duì)tableview的contentOffset進(jìn)行實(shí)時(shí)監(jiān)測(cè),很容易地使用KVO來(lái)實(shí)現(xiàn)為。在初始化方法中加入:

[_tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

在dealloc中移除KVO監(jiān)聽(tīng):[_tableView removeObserver:self forKeyPath:@"contentOffset" context:nil];添加默認(rèn)的響應(yīng)回調(diào)方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object? ? ? ? ? ? ? ? ? ? ? ? change:(NSDictionary *)change context:(void *)context{? ? ??

?[self doSomethingWhenContentOffsetChanges];

}

好了,KVO實(shí)現(xiàn)就到此完美結(jié)束了,拜拜。。。開(kāi)個(gè)玩笑,肯定沒(méi)這么簡(jiǎn)單的,這樣的代碼太粗糙了,當(dāng)你在controller中添加多個(gè)KVO時(shí),所有的回調(diào)都是走同上述函數(shù),那就必須對(duì)觸發(fā)回調(diào)函數(shù)的來(lái)源進(jìn)行判斷。

判斷如下:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object? ? ? ? ? ? ? ? ? ? ? ? change:(NSDictionary *)change context:(void *)context{? ??

if (object == _tableView && [keyPath isEqualToString:@"contentOffset"])?

{

[self doSomethingWhenContentOffsetChanges];}

?}

你以為這樣就結(jié)束了嗎?答案是否定的!我們假設(shè)當(dāng)前類(lèi)(在例子中為UITableViewController)還有父類(lèi),并且父類(lèi)也有自己綁定了一些其他KVO呢?我們看到,上述回調(diào)函數(shù)體中只有一個(gè)判斷,如果這個(gè)if不成立,這次KVO事件的觸發(fā)就會(huì)到此中斷了。但事實(shí)上,若當(dāng)前類(lèi)無(wú)法捕捉到這個(gè)KVO,那很有可能是在他的superClass,或者super-superClass...中,上述處理砍斷了這個(gè)鏈。

合理的處理方式應(yīng)該是這樣的:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object? ? ? ? ? ? ? ? ? ? ? ? change:(NSDictionary *)change context:(void *)context{? ??

if (object == _tableView && [keyPath isEqualToString:@"contentOffset"]) {??

? ? ? [self doSomethingWhenContentOffsetChanges];}?

else {? ? ? ?

?[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];}

} 這樣就結(jié)束了嗎?

答案仍舊是否定的。潛在的問(wèn)題有可能出現(xiàn)在dealloc中對(duì)KVO的注銷(xiāo)上。KVO的一種缺陷(其實(shí)不能稱(chēng)為缺陷,應(yīng)該稱(chēng)為特性)是,當(dāng)對(duì)同一個(gè)keypath進(jìn)行兩次removeObserver時(shí)會(huì)導(dǎo)致程序crash,這種情況常常出現(xiàn)在父類(lèi)有一個(gè)kvo,父類(lèi)在dealloc中remove了一次,子類(lèi)又remove了一次的情況下。不要以為這種情況很少出現(xiàn)!當(dāng)你封裝framework開(kāi)源給別人用或者多人協(xié)作開(kāi)發(fā)時(shí)是有可能出現(xiàn)的,而且這種crash很難發(fā)現(xiàn)。不知道你發(fā)現(xiàn)沒(méi),目前的代碼中context字段都是nil,那能否利用該字段來(lái)標(biāo)識(shí)出到底kvo是superClass注冊(cè)的,還是self注冊(cè)的?回答是可以的。我們可以分別在父類(lèi)以及本類(lèi)中定義各自的context字符串,比如在本類(lèi)中定義context為@"ThisIsMyKVOContextNotSuper";然后在dealloc中remove observer時(shí)指定移除的自身添加的observer。這樣iOS就能知道移除的是自己的kvo,而不是父類(lèi)中的kvo,避免二次remove造成crash。寫(xiě)作本文來(lái)由:? iOS默認(rèn)不支持對(duì)數(shù)組的KVO,因?yàn)槠胀ǚ绞奖O(jiān)聽(tīng)的對(duì)象的地址的變化,而數(shù)組地址不變,而是里面的值發(fā)生了改變整個(gè)過(guò)程需要三個(gè)步驟 (與普通監(jiān)聽(tīng)一致)

*? 第一步 建立觀察者及觀察的對(duì)象 ? ?

*? 第二步 處理key的變化(根據(jù)key的變化刷新UI)? ??

*? 第三步 移除觀察者*/[objc] view plain copy數(shù)組不能放在UIViewController里面,在這里面的數(shù)組是監(jiān)聽(tīng)不到數(shù)組大小的變化的,需要將需要監(jiān)聽(tīng)的數(shù)組封裝到model里面<? model類(lèi)為: 將監(jiān)聽(tīng)的數(shù)組封裝到model里,不能監(jiān)聽(tīng)UIViewController里面的數(shù)組兩個(gè)屬性 一個(gè) 字符串類(lèi)的姓名,一個(gè)數(shù)組類(lèi)的modelArray,我們需要的就是監(jiān)聽(tīng)modelArray里面元素的變化[objc] view plain copy@interface model : NSObject? @property(nonatomic, copy)NSString *name;? @property(nonatomic, retain)NSMutableArray *modelArray;??

1 建立觀察者及觀察的對(duì)象?

?第一步? 建立觀察者及觀察的對(duì)象? ? [_modeladdObserver:selfforKeyPath:@"modelArray"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:NULL];??

第二步 處理key的變化(根據(jù)key的變化刷新UI)? ? 最重要的就是添加數(shù)據(jù)這里[objc] view plain copy不能這樣 [_model.modelArray addObject]方法,需要這樣調(diào)用? [[_model mutableArrayValueForKey:@"modelArray"] addObject:str];原因稍后說(shuō)明。? -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context[objc] view plain copy{? ? ? if ([keyPath isEqualToString:@"modelArray"]) {? ? ? ? ? [_tableView reloadData];? ? ? }? }? ? ??

第三步 移除觀察者[objc] view plain copyif (_model != nil) {? ? ? [_model removeObserver:self forKeyPath:@"modelArray"];? }? 以下附上本文代碼:代碼中涉及三點(diǎn)

1 根據(jù)數(shù)組動(dòng)態(tài)刷新tableview;2 定時(shí)器的使用(涉及循環(huán)引用問(wèn)題);3 使用KVC優(yōu)化model的初始化代碼。沒(méi)找到上傳整個(gè)工程的方法,

暫時(shí)附上代碼1? NSTimer相關(guān)//為防止controller和nstimer之間的循環(huán)引用,delegate指向當(dāng)前單例,而不指向controller? ??

@interface NSTimer (DelegateSelf)? ?

?+(NSTimer *)scheduledTimerWithTimeInterval:(int)timeInterval block:(void(^)())block repeats:(BOOL)yesOrNo;? ??

@end ?

? #import "NSTimer+DelegateSelf.h"? ?

?@implementation NSTimer (DelegateSelf)? ??

+(NSTimer *)scheduledTimerWithTimeInterval:(int)timeInterval block:(void(^)())block repeats:(BOOL)yesOrNo? {? ? ?

?return [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(callBlock:) userInfo:[block copy] repeats:yesOrNo];? }? ? ?

?+(void)callBlock:(NSTimer *)timer? {? ? ?

?void(^block)() = timer.userInfo;? ? ?

?if (block != nil) {? ? ? ? ? block();? ? ? }? }? ??

@end??

2 model相關(guān)

? ?@interface model : NSObject??

@property(nonatomic, copy)NSString *name;? @property(nonatomic, retain)NSMutableArray *modelArray;??

? -(id)initWithDic:(NSDictionary *)dic;? ? @end?

?#import "model.h"? ??

@implementation model? ?

?-(id)initWithDic:(NSDictionary *)dic? {? ??

? self = [super init];? ? ??

if (self) {? ? ? ? ??

[self setValuesForKeysWithDictionary:dic];? ? ?

?}? ? ? ? ? ?

?return self;? }? ?

?-(void)setValue:(id)value forUndefinedKey:(NSString *)key? {? ? ? NSLog(@"undefine key ---%@",key);? }? ? @end??

3 UIViewController相關(guān) ??

* 第一步 建立觀察者及觀察的對(duì)象? ?

*? 第二步 處理key的變化(根據(jù)key的變化刷新UI)? ?

?*? 第三步 移除觀察者? */? ??

#import "RootViewController.h"??

#import "NSTimer+DelegateSelf.h"??

#import "model.h"? ?

?#define TimeInterval 3.0? ??

@interface RootViewController ()

@property(nonatomic, retain)NSTimer *timer;

@property(nonatomic, retain)UITableView? ? *tableView;

@property(nonatomic, retain)model *model;

@end

@implementation RootViewController

//注意在什么地方注銷(xiāo)觀察者

- (void)dealloc

{

//第三步

if (_model != nil) {

[_model removeObserver:self forKeyPath:@"modelArray"];

}

//停止定時(shí)器

if (_timer != nil) {

[_timer invalidate];

_timer = nil;

}

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

NSDictionary *dic = [NSDictionary dictionaryWithObject:[NSMutableArray arrayWithCapacity:0] forKey:@"modelArray"];

self.model = [[model alloc] initWithDic:dic];

}

return self;

}

- (void)viewDidLoad

{

[super viewDidLoad];

//第一步

[_model addObserver:self forKeyPath:@"modelArray" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

_tableView.delegate? ? ? ? = self;

_tableView.dataSource? ? ? = self;

_tableView.backgroundColor = [UIColor lightGrayColor];

[self.view addSubview:_tableView];

//定時(shí)添加數(shù)據(jù)

[self startTimer];

}

//添加定時(shí)器

-(void)startTimer

{

__block RootViewController *bself = self;

_timer = [NSTimer scheduledTimerWithTimeInterval:TimeInterval block:^{

[bself changeArray];

} repeats:YES];

}

//增加數(shù)組中的元素 自動(dòng)刷新tableview

-(void)changeArray

{

NSString *str = [NSString stringWithFormat:@"%d",arc4random()%100];

[[_model mutableArrayValueForKey:@"modelArray"] addObject:str];

}

//第二步 處理變化

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(voidvoid *)context

{

if ([keyPath isEqualToString:@"modelArray"]) {

[_tableView reloadData];

}

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return? [_model.modelArray count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

{

static NSString *cellidentifier = @"cellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier];

}

cell.textLabel.text = _model.modelArray[indexPath.row];

return cell;

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

對(duì)時(shí)鐘的運(yùn)用 根據(jù)時(shí)鐘更新uilabel的數(shù)值

-(void)updateLabel:(CGFloat)percent withAnimationTime:(CGFloat)animationTime{

CGFloat startPercent = [self.text floatValue];

CGFloat endPercent = percent*10;

CGFloat intever = animationTime/fabsf(endPercent - startPercent);

timer = [NSTimer scheduledTimerWithTimeInterval:intever target:self selector:@selector(IncrementAction:) userInfo:[NSNumber numberWithFloat:percent] repeats:YES];

[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];

[timer fire];

}

-(void)IncrementAction:(NSTimer *)time{

CGFloat change = [self.text integerValue];

CGFloat tt=[time.userInfo integerValue];

CGFloat dd=[time.userInfo floatValue]-tt;

if(change < [time.userInfo floatValue]){

change++;

}

else{

change--;

}

self.text = [NSString stringWithFormat:@"%.1f",(change+dd)];

if ([self.text integerValue] == [time.userInfo integerValue]) {

[time invalidate];

}

}

-(void)clear{

self.text = @"0";

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容