[英]Accessing controller from model
我有以下 class 设计:
一个 controller class 和一个 model class 都继承自 NSobject;
具有来自 controller 的 IBoutlets 的 UI;
model class 扫描一组文件的属性并写入文件(使用循环);
UI 必须显示正在扫描的当前文件的名称。
如何使 model class 与 controller 通信?
I have made an object of the model inside the controller so to avoid circularity I cannot make an instance of controller inside the model class. 关于如何实现这一点的任何建议?
在模型的.h 中定义一个协议,如下所示:
@protocol FileScannerDelegate
@required
- (void)fileScanner:(FileScannerClass *)fileScanner willScanFile:(NSString *);
@end
添加一个assign
的新属性以保存对委托的引用。 这需要分配以避免循环引用
@property (nonatomic, assign) id<FileScannerDelegate> delegate;
在 model.m 中,您正在扫描您调用的下一个文件
[delegate fileScanner:self willScanFile:fileName];
在控制器的.h中你需要说你遵循协议
@interface MyController : UIViewController <FileScannerDelegate>
在 controller.m 中。 当您在 controller 中实例化文件扫描器时,您需要将 controller 设置为委托
fileScanner = [[FileScannerClass alloc] init];
fileScanner.delegate = self;
然后实现你说的方法
- (void)fileScanner:(FileScannerClass *)fileScanner willScanFile:(NSString *)
{
...
// update the UI
}
提供 model 并参考 controller。
@class MyController
@interface MyModel:NSObject
@property (readwrite,assign) MyController *controller;
@end
并实施
#include "MyController.h"
@implementation MyModel
@synthesize controller;
-(void)somethingHappenedToMe
{
[controller updateYourself:self];
}
@end
您可以使用委托和私有方法将自己抽象化,但最终您仍然希望 model 实例与您的 controller 实例对话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.