0

I'm trying to observe a property of my AppDelegate in order to update a tableview. It's a little complicated, so here's some of my code.

I want to update the content of a UITableView whenever an array is updated. I feel like there's a more efficient way to do this but can't seem to figure it out. I've read through Apple's documentation online and am kinda confused. Thanks ahead of time!! :)

//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
rmaddy
  • 314,917
  • 42
  • 532
  • 579
felix_xiao
  • 1,608
  • 5
  • 21
  • 29

1 Answers1

0

UPDATE:

I would encourage you to make the view controller subscribe to the notification in the setter of the data model. It will conveniently keep subscriptions-unsubscriptions in one place:

- (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
}

The owner of the view controller is responsible to set the proper data model on creation and when it changes.

Davyd Geyl
  • 4,578
  • 1
  • 28
  • 35
  • Why can't two view controllers observe a single data model? It works just fine. Notice that in the OP's question, the data modal does not have a delegate. Normal KVO is being used. – rmaddy Jul 15 '13 at 04:34
  • Nothing wrong, I misunderstood usage of delegate. Disregard my answer, I will update it. – Davyd Geyl Jul 15 '13 at 04:52