-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAIMObserver.m
More file actions
60 lines (49 loc) · 1.65 KB
/
AIMObserver.m
File metadata and controls
60 lines (49 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// AIMObserver.m
//
// Created by Maciej Gad on 29.07.2015.
// Copyright (c) 2015 All in Mobile. All rights reserved.
//
#import "AIMObserver.h"
@interface AIMObserver ()
@property (strong, nonatomic) NSObject *observed;
@property (strong, nonatomic) NSString *keyPath;
@property (copy, nonatomic) void (^onChange)(NSDictionary *change);
@end
@implementation AIMObserver
+ (instancetype)observed:(NSObject *)obj keyPath:(NSString *)keyPath onChange:(void(^)(NSDictionary *change))onChange {
if (!obj || !keyPath || !onChange) {
return nil;
}
return [[AIMObserver alloc] initWithObserved:obj keyPath:keyPath onChange:onChange];
}
- (instancetype)initWithObserved:(NSObject *)obj keyPath:(NSString *)keyPath onChange:(void(^)(NSDictionary *))onChange{
self = [super init];
if (self) {
self.observed = obj;
self.keyPath = keyPath;
self.onChange = onChange;
[self startObserve];
}
return self;
}
- (instancetype)init {
[NSException raise:@"Invalid method" format:@"use [AIMObserver observed:keyPath:onChange:] instead"];
return nil;
}
- (void)startObserve{
[self.observed addObserver:self forKeyPath:self.keyPath options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld|NSKeyValueObservingOptionInitial context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (![keyPath isEqualToString:self.keyPath]) {
return;
}
if (!self.onChange) {
return;
}
self.onChange(change);
}
- (void)dealloc {
[self.observed removeObserver:self forKeyPath:self.keyPath];
}
@end