MVC:不同类中方法的传递

妇科

我正在使用MVC设计模式实现应用程序iOS。

该应用程序有5个界面,我以这种方式进行操作:

  • AppDelegate(CONTROLLER);
  • WebServiceModel(MODEL);
  • 5个界面,代表应用程序的5个视图(VIEWS)。

在模型中,我实现了一种将消息发送到Web服务以请求数据的方法。根据MVC,控制器必须从模型接收数据并将其发送到视图,因此在控制器中,我已实现了一种调用模型方法的方法。在视图中,我实例化一个对象Controller并调用Controller方法。当应用程序启动时,Xcode仅启动AppDelegate(控制器)方法的命令,而不会读取对Model方法的调用。

如果推理有误,我深表歉意。总之:

// AppDelegate.h

#import "WebServiceModel.h"
@interface AppDelegate: UIResponder <UIApplicationDelegate> {
WebServiceModel *model;
}

@property (retain, nonatomic) WebServiceModel *model;
- (void) func;
_________________

// AppDelegate.m

@implementation AppDelegate
@syntesize model;

- (void) func {
    NSLog(@"OK!");
    [model function];
}
@end
_________________

// WebServiceModel.h

#import "AppDelegate.h"
@interface WebServiceModel: NSObject <NSXMLParserDelegate> {
AppDelegate *controller;
}

- (void) function;
_________________

// WebServiceModel.m

@implementation WebServiceModel

- (void) function {
    NSLog(@"YES!");
    //other instructions
}
@end
_________________

// View Controller.h

#import "AppDelegate.h"
@interface ViewController: UIViewController {
AppDelegate *controller;
}

_________________

// ViewController.m

@implementation ViewController

- (void) viewDidLoad {
    NSLog(@"OH!");
    controller = (AppDelegate *) [[UIApplication sharedApplication] delegate];
    [controller func];
}
@end

当应用启动时,在“所有输出”中您只会看到“ OH!”。和“确定!”,但没有“确定!”。

因为没有调用模型的方法“函数”?

感谢那些回答我的人!

戴维·道尔(David Doyle)

您实际上尚未创建模型对象的实例,因此实际上发生的是在nil上调用-function。要解决此问题很容易,请将以下方法添加到AppDelegate:

- (id)init
{
  self = [super init];
  if (nil != self)
  {
    self.model = [[WebServiceModel alloc] init];
  }
  return self;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章