ios - 多次调用observeValueForKeyPath

标签 ios objective-c iphone key-value-coding

我有一个自定义容器导航。我有一个日记 View Controller 和一个日记详细信息 View Controller 。当用户点击日记中的图片时,它将使用 cycleFromViewController:toViewController 方法转到日记详细信息,如 Apple 文档中关于容器 View Controller 的描述。

当详细 View 加载时,我希望容器 View Controller 删除它的一个 subview 并添加另一个。我使用 KVC 来完成这个任务。这是我第一次使用KVC。 addObserver 方法在 viewWillAppear 日记详细 vc 中。

问题:日记详情 VC被加载,第一次调用observeValueForKeypath,第二次调用两次,以此类推。此外,在 observeValueForKeypath 中,我添加了一个 subview - UIButton - 当它被点击时,再次调用 cycleFromViewController:toViewController 并且之前的 subview 被添加回来。它在第一次运行时有效,但在随后的运行中,原始 subview 不会被添加回来,UIButton 只是停留在周围。

日记详情.m

-(void)viewWillAppear:(BOOL)animated{

[self addObserver:self.parentViewController forKeyPath:@"didLoadNumber" options:0 context:nil];

[self setValue:[NSNumber numberWithInt:0] forKey:@"didLoadNumber"];}

主容器 VC(观察者/父 VC)

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


    NSLog(@"KVO called");
    [self.usernameLabel removeFromSuperview];
    self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(12, 28, 28, 28)];


    self.backButton.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.backButton];

    [self.backButton addTarget:self action:@selector(removeButtonAndAddLogo)
              forControlEvents:UIControlEventTouchUpInside];

-(void)removeButtonAndAddLogo{

NSLog(@"got to remove button");
[self.backButton removeFromSuperview];
self.usernameLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 28, 28, 28)];
self.usernameLabel.text = @"username";
self.usernameLabel.textColor = [UIColor blackColor];
[self.view addSubview:self.usernameLabel];

[self cycleFromViewController:self.diaryViewController.diaryDetailVC toViewController:self.diaryViewController];

最佳答案

为此,您需要在 viewWillDisappear 方法中将其删除。如果您多次访问此 View Controller ,它会一次又一次地注册此通知,并且每当您调用此通知时,它都会调用多次(您注册的次数)。

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [self addObserver:self.parentViewController forKeyPath:@"didLoadNumber" options:0 context:nil];
    [self removeObserver:self.parentViewController forKeyPath:@"didLoadNumber"];
}

希望对你有帮助

关于ios - 多次调用observeValueForKeyPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112757/

相关文章:

iphone - 以正确的方式检测 UITextField 中的退格键

ios - NSSortDescriptor 对许多关系子属性求和

Objective-C:检索 Class 实例的父类(super class)的首选方法

iphone - 获取 NSCollectionViewItem 的frame.size

ios - 在 iOS 中显示虚拟键盘时固定位置不起作用

iphone - 单元测试很棒,但是

ios - Objective-C -NSMutablearray 特定索引存储在另一个数组中

ios - 将 UITableView 添加为 subview 时,didSelectRowAtIndexPath 不会触发单元格

iphone - 在仿射变换上放大 iPhone "vector-based graphics"

ios - NSDictionary 丢失数据?