我正在尝试理解如何在此链接中实现真正的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的帮助下,我无法使用具有多个参数的选择器。例如,
- (void) DataManager:(DataManager *) dm withObj1:(Obj1*) obj1 Obj1:(Obj2*) obj2 Obj3:(Obj3*) obj3
非常感谢!
答案 0 :(得分:1)
But problem is that with the help of KVO and NSNotificationCenter i can not use selectors with more than 1 argument.
你可以!!!
将所有选择器存储在数组或字典中,然后传递该单个对象。
答案 1 :(得分:0)
我认为使用委托或块是理想的。要在视图控制器中获得回调,您可以使用委托方法或块。我认为这将是MVC设计模式的理想方法。
答案 2 :(得分:0)
KVO通常是更好的选择。例如:
在IDataManager中:
- (void) handleLoadedNews:(NSArray *) loadedNews
{
[self willChangeValueForKey:@"feedsArray"]; //Also, see - (void)willChange:(NSKeyValueChange)changeKind valuesAtIndexes:(NSIndexSet *)indexes forKey:(NSString *)key
[self.feedsArray addObjectsFromArray:arr];
[self didChangeValueForKey:@"feedsArray"]; //Also, see - (void)didChange:(NSKeyValueChange)changeKind valuesAtIndexes:(NSIndexSet *)indexes forKey:(NSString *)key
}
并且,在ViewController中:
- (void) viewDidLoad {
....
[[IADataManager sharedInstance] addObserver:self forKeyPath:@"feedsArray" options:0 context:NULL];
}
- (void) viewWillUnload {
....
[[IADataManager sharedInstance] removeObserver:self forKeyPath:@"feedsArray"];
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//if keyPath is "feedsArray", refresh my views
}