0

テーブルビューを更新するために、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
4

1 に答える 1

0

アップデート:

ビュー コントローラーがデータ モデルのセッターで通知をサブスクライブするようにすることをお勧めします。サブスクリプションとサブスクリプション解除を 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
}

ビュー コントローラの所有者は、作成時と変更時に適切なデータ モデルを設定する責任があります。

于 2013-07-15T04:30:14.680 に答える