Reputation: 1675
Is it a good pattern to add a @protocol to a Model class and implement it in the Controller?
Here is the a code which I use to send message to reload UITableView when My Model data changes, is it a good approach for object c codding?:
MyModel.h
@protocol myModelDelegate
{
(void) refreshTableView:(id) sender;
}
@end
@interface MyModel
{
@property (nonatomic,strong) (NSArray *) myData;
@property (nonatomic,weak) (id) <myModelDelegate> delegate;
}
@end
MyModel.m
@implementation MyModel
@synthesize myData=_myData;
- (NSArray*) myData {
if(!_myData) {
_myData= [[NSArray alloc] init];
}
return _myData;
}
- (void) setMyData: (NSArray*) myData
{
if (_myData != myData) {
_myData=myData;
[delegate refreshTableView:self];
}
}
@end
myDataController.h
...
@interface MyDataController: UITableViewController <myModelDelegate>
...
myDataController.m
@interface MyDataController()
@property (nonatomic,strong) (MyModel *) model;
@end
@implementation MyDataController
@synthesize model=_model;
-(MyModel *) model
{
if(!_model)
{
_model=[[MyModel alloc]init];
model.delegate=self;
}
return _model;
}
...
- (void) refreshTableView: (id) sender
{
[TableView reloadData];
}
...
@end
Upvotes: 1
Views: 630
Reputation: 69027
I don't see any problem with this design.
The only thing I would change is the signature of the delegate method into:
-(void)modelDidChange:(MyModel*)model;
This is more in line with best-practices you see around about naming of delegate methods, and also hints to a broader semantics of the method: the model will "signal' the fact that it changed; the delegate will take an action upon that (i.e., refreshing a table if it's a table; storing the model content, if it's a perstistence component, etc.)
Upvotes: 3