我想要做的总结。
我的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“计时器触发...”
我的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];
}
观察:NSLogs“收到KVO”都没有打印出来。
有谁能让我知道我做错了什么?
第二个问题,如何从Xcode的调试窗口中找到存储在mailText中的值。我试过po mailText,但那没用。
答案 0 :(得分:0)
发现问题,从未调用过MailDispViewController的viewDIdLoad,因为我从未进入此视图。但是当我尝试在转入MailDispViewCOntroller并返回主视图后尝试更新self.mailText时,我遇到了另一个问题(EXC_BAD_ACCESS)。
我不允许发布图片。所以我不能给屏幕截图。因此,我将尝试用文字解释
Main Storyboard由连接到TableViewController的导航控制器(初始入口点)组成,有两行。 TableViewCOntroller的第二行连接到带有TextView的ViewController(我在下面调用这个二级视图)。
当我进入二级视图并返回主视图时,我在计时器到期时获得EXC_BAD_ACCESS,并且在我的AppDelegate中更新了MailText。如果我在计时器到期时仍然在辅助视图中,则没有问题,我可以看到在计时器到期后设置的更新文本。
谁能告诉我发生了什么?
答案 1 :(得分:0)
答案是:不要打电话
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
当super不会处理keyPath时。这意味着,只要它们的关键路径是您的或上下文是您的,就不应称为超级。仅调用super以确保可以定期观察代码中的kvo。