KVO-不会调用observeValueForKeyPath

问题描述 投票:0回答:2

我正在尝试做的事情的摘要。

我在AppDelegate.h中有一个名为mailText的NSMutableString属性,每当更改此属性的值时,我都希望通知viewController并将其本地IBOutlet属性的值设置为新值。最终,APpDelegate将根据收到的推送通知更改字符串。

为了进行测试,我在APpDelegate中触发了一个计时器,并在计时器到期时更改mailText的值。但是,发生这种情况时,不会在我的ViewCOntroller中调用addObserver方法]

AppDelegate.h中的代码

@property (strong, nonatomic) NSMutableString *mailText;

AppDelegate.m中的代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ......

    self.mailText = [NSMutableString string] ;
    self.mailText = (NSMutableString *)@"First text" ;

    [self enableTimer] ;
    ......
}

-(void) enableTimer
{
    NSTimer *timer = nil ;

    timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(updateText) userInfo:nil repeats:NO] ;

    //self.myTimer = timer ;

}

-(void) updateText
{
    self.mailText = (NSMutableString *)@"Changed to second text..aaanjanalnal .. jansjanskanska" ;
    NSLog(@"Timer fired...updating mailtext") ;

}

观察:我在模拟器上运行应用程序时,正在打印NSLog“ Timer fired ...”

ViewController.h中的代码

@interface MailDispViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextView *mailDispText;

@end

ViewController.m中的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [(AppDelegate *)[[UIApplication sharedApplication] delegate] addObserver:self forKeyPath:@"mailText" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    NSLog(@"received a KVO") ;

    if ([keyPath isEqual:@"mailText"]) {
        NSLog(@"received a KVO for mailtext") ;
        self.mailDispText.text = [change objectForKey:NSKeyValueChangeNewKey];

     }
    /*
     Be sure to call the superclass's implementation *if it implements it*.
     NSObject does not implement the method.
     */
    [super observeValueForKeyPath:keyPath
                         ofObject:object
                           change:change
                          context:context];
 }

观察:均未打印“接收到KVO”的两个NSLogs。

有人可以让我知道我在做什么错吗?

第二个问题,如何从Xcode的调试窗口中找到存储在mailText中的值。我尝试了po mailText,但是没有用。

我正在尝试做的事情的摘要。我的AppDelegate.h中有一个名为mailText的NSMutableString属性,每当更改此属性的值时,我都希望通知我的viewController并对其进行通知...

ios objective-c key-value-observing
2个回答
0
投票

发现了问题,因为我从未涉足此视图,所以从未调用过MailDispViewController的viewDIdLoad。但是现在我遇到另一个问题(EXC_BAD_ACCESS)时,我在进入MailDispViewCOntroller后尝试更新self.mailText并返回到主视图。


0
投票

答案是:请勿致电

© www.soinside.com 2019 - 2024. All rights reserved.