我试图了解如何实现真正的 Cocoa MVC,如图 4-7 所示。
这是一个链接
图 4-7 显示模型使用模式观察器来通知控制器(被动 MVC)。我以这种方式在我的模型中实现观察者
@interface IADataManager : NSObject
//MARK: Parsed Feed With IANewsDataObj
@property (nonatomic,retain) NSMutableArray *feedArray;
//MARK: Model use Singelton Pattern
+ (IADataManager *) sharedInstance;
//MARK: Observation methods
- (void) addListener:(id<IADataManagerListener>) listener;
- (void) removeListener:(id<IADataManagerListener>) listener;
//MARK: Business Logic
- (void) loadFeedFromNetwork;
- (void) loadFeedFromDataBase;
- (void) loadImageForTarget:(id<IADataManagerListener>) target
AtIndexPath:(NSIndexPath *) indPath;
- (void) saveFeedToDataBase;
@end
@protocol IADataManagerListener <NSObject>
- (void) IADataManager :(IADataManager *) dataMng
didRefreshWithError :(NSError *) error;
- (void) IADataManager :(IADataManager *) dataMng
didLoadImageForIndexPath :(NSIndexPath *) indexPath;
- (void) IADataManager :(IADataManager *) dataMng
didLoadWithError :(NSError *) error;
@end
- (void) addListener:(id<IADataManagerListener>) listener
{
if([self.listeners indexOfObject:listener] == NSNotFound && listener)
[self.listeners addObject:listener];
}
- (void) removeListener:(id<IADataManagerListener>) listener
{
if([self.listeners indexOfObject:listener] !=NSNotFound && listener)
[self.listeners removeObject:listener];
}
//Notification example
- (void) handleLoadedNews:(NSArray *) loadedNews
{
[self.feedArray addObjectsFromArray:loadedNews];
[self.listeners enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
objc_msgSend(obj, @selector(IADataManager:didRefreshWithError:),self,nil);
}];
}
我想知道,是否有更好的方法在模型中实现观察者?例如使用 KVO 或 NSNotificationCenter。但问题是,在 KVO 和 NSNotificationCenter 的帮助下,我不能使用超过 1 个参数的选择器。例如,
- (void) DataManager:(DataManager *) dm withObj1:(Obj1*) obj1 Obj1:(Obj2*) obj2 Obj3:(Obj3*) obj3
非常感谢!