在Objective-C中,使用鍵值觀察時,我有一個包含accountDomestic屬性和person屬性的Bank類。該人被添加到觀察賬戶國內財產。我在Bank類中有一個static void *bankContext = & bankContext
作爲上下文。但是,在更改accountDomestic屬性後,由於上下文和bankContext在Person中的-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
方法不匹配,未能正確顯示舊值和新值。關鍵值觀察上下文不起作用
代碼如下,首先是銀行類:
Bank.h
#import <Foundation/Foundation.h>
#import "Person.h"
static void * const bankContext = &bankContext;
@class Person;
@interface Bank : NSObject
@property (nonatomic, strong) NSNumber* accountDomestic;
@property (nonatomic, strong) Person* person;
-(instancetype)initWithPerson:(Person *)person;
@end
Bank.m
@implementation
-(instancetype)initWithPerson:(Person *)person{
if(self = [super init]){
_person = person;
[self addObserver:_person
forKeyPath:NSStringFromSelector(@selector(accountDomestic))
options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew
context:bankContext];
}
return self;
}
-(void)dealloc{
[self removeObserver:_person forKeyPath:NSStringFromSelector(@selector(accountDomestic))];
}
@end
則是Person類:
Person.h
#import <Foundation/Foundation.h>
#import "Bank.h"
@interface Person : NSObject
@end
Person.m
#import "Person.h"
@implementation Person
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"context: %p",context);
NSLog(@"bankContext: %p",bankContext);
if(context == bankContext){
if([keyPath isEqualToString:NSStringFromSelector(@selector(accountDomestic))]){
NSString *oldValue = change[NSKeyValueChangeOldKey];
NSString *newValue = change[NSKeyValueChangeNewKey];
NSLog(@"--------------------------");
NSLog(@"accountDomestic old value: %@", oldValue);
NSLog(@"accountDomestic new value: %@", newValue);
}
}
}
@end
最後是視圖控制器類
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m
#import "ViewController.h"
#import "Bank.h"
#import "Person.h"
@interface ViewController()
@property (nonatomic, strong) Bank *bank;
@property (nonatomic, strong) Person *person;
@property (nonatomic, strong) NSNumber *delta;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.person = [[Person alloc] init];
self.delta = @10;
self.bank = [[Bank alloc] initWithPerson:self.person];
}
- (IBAction)accountDomesticIncreaseButtonDidTouch:(id)sender {
self.bank.accountDomestic = self.delta;
int temp = [self.delta intValue];
temp += 10;
self.delta = [NSNumber numberWithInt:temp];
}
@end
後我點擊按鈕,accountDomestic的新舊值不顯示。你可以看到背景和bankContext值不相等,如下圖所示:
有沒有人有任何想法?
如果你使用靜態,那麼這個類如果有效地簡化爲單例。你爲什麼要這樣限制班級? – Droppy
這是建議在這篇文章http://nshipster.com/key-value-observing/。作爲一個令牌。如果我不關心不同的事例,只要是同一個班級,我認爲這很好。問題的關鍵在於爲什麼這個概念和bankContext不相等。 – Johnson
好的 - 我的錯。我把它拿回來:) – Droppy