【问题标题】:Observe Property of Property观察财产的性质
【发布时间】:2013-07-15 12:57:02
【问题描述】:

我正在尝试观察我的 AppDelegate 的属性以更新表格视图。这有点复杂,所以这是我的一些代码。

我想在数组更新时更新 UITableView 的内容。我觉得有一种更有效的方法可以做到这一点,但似乎无法弄清楚。我已经在线阅读了 Apple 的文档,有点困惑。提前谢谢!! :)

//Game.h
@interface Game: NSObject
@property (strong,nonatomic) NSMutableArray *myArray;
@end

//AppDelegate.h
#import "Game.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong,nonatomic) Game *myGame;
@end

//ViewController.m
#import "AppDelegate.h"
@implementation ViewController
//...
- (void)viewDidLoad
{
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] addObserver:self forKeyPath:@"myGame" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //THIS METHOD NEVER GETS CALLED
    NSLog(@"change observed");
    [self.tableView reloadData];
}
- (void)dealloc
{
    [(AppDelegate*)[[UIApplication sharedApplication] delegate] removeObserver:self forKeyPath:@"myGame"];
}
//...
@end

【问题讨论】:

标签: ios objective-c observers addobserver


【解决方案1】:

更新:

我鼓励您让视图控制器订阅数据模型设置器中的通知。它将方便地将订阅-取消订阅保存在一个地方:

- (void)setDataModel:(YourDataModelClass*)dataModel
{
    [_dataModel removeObserver:self forKeyPath:@"myGame" context:nil];

    _dataModel = dataModel; // I hope you use ARC, otherwise check if the pointers are different.

    if (_dataModel != nil)
        [_dataModel addObserver:self forKeyPath:@"myGame" options:0 context:nil];
}

- (void)dataModelDidUpdate
{
    [self.tableView reloadData];
}

- (void)dealloc
{
    self.dataModel = nil; //An easy way to unsubscribe
}

视图控制器的所有者负责在创建和更改时设置正确的数据模型。

【讨论】:

  • 为什么两个视图控制器不能观察一个数据模型?它工作得很好。请注意,在 OP 的问题中,数据模式没有委托。正在使用普通 KVO。
  • 没有错,我误解了委托的用法。无视我的回答,我会更新的。
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-03
  • 2023-04-08
相关资源
最近更新 更多