【问题标题】:iOS Communication between Model and ViewControlleriOS 模型和 ViewController 之间的通信
【发布时间】:2012-06-02 07:01:54
【问题描述】:

我正在开发一个基于 Apple 提供的 Master-View 模板的应用程序(它包含两个 ViewController,MasterViewController 和 DetailViewController)。我添加了一个模型来与我的服务器通信。

但是,当我的 Model 收到来自服务器的消息时,它需要调用 MasterViewController 或 DetailViewController 类中的方法。我该怎么做?

非常感谢所有帮助。

【问题讨论】:

  • 你的型号是什么? MVC 中的 M 模型?

标签: ios model-view-controller


【解决方案1】:

块是要走的路。

您需要在 ViewController 中引用您的模型。当您想要更新数据时,您向模型发送一条消息并将块作为参数传递给它,当从服务器接收到响应时,它将被调用。

例如:

视图控制器

[self.model fetchDataFromRemoteWithCompletionHandler:^(id responseObject, NSError *error)
{
    // responseObject is the Server Response
    // error - Any Network error
}];

型号

-(void)fetchDataFromRemoteWithCompletionHandler:(void(^)(id, NSError*))onComplete
{
    // Make Network Calls
    // Process Response
    // Return data back through block
    onComplete(foobarResponse, error);
}

【讨论】:

    【解决方案2】:

    您应该使用可选的协议委托方法。我有一个答案,例如如何在这个PO 中设置委托方法。

    【讨论】:

      【解决方案3】:

      实际上MVC pattern that Apple proposes 允许从模型到控制器的通知。

      实现此目标的一个好方法是在您的数据更改时通过NSNotificationCenter 传递NSNotification 对象,并提供有关更改内容的信息,并让侦听器处理它。

      【讨论】:

      • 但是如何通过 NSNotifications 发送字符串?看来我所能做的就是发送一个空通知
      • 请参考Apple's documentation on NSNotificationCenter。您可以使用 - (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender 为您的通知分配名称和发件人对象。
      • 例如您可以将数据对象设为发送者,通知名称可以是一个字符串,例如:@"senderNamePropertyChanged"(我建议您使用常量来定义允许的通知名称)。跨度>
      • 我意识到我可以使用可选的 UserInfo 参数。
      【解决方案4】:

      您可以从模型中触发通知,这些通知由 Master 和 Detail View 控制器处理。

      在模型中:

      - (void)receivedMessageFromServer {
          // Fire the notification
          [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedData" 
                                                              object:nil];   
      }
      

      在您的视图控制器中处理“ReceivedData”通知:

      - (void)viewDidLoad {
          [NSNotificationCenter defaultCenter] addObserver:self 
                                                  selector:@selector(receivedDataNotification:) 
                                                      name:@"ReceivedData" 
                                                    object:nil];
      }
      
      - (void)receivedDataNotification:(id)object {
          NSLog(@"Received Data!");
      }
      

      【讨论】:

      • 但是如何通过 NSNotifications 发送字符串?看来我所能做的就是发送一个空通知
      • 使用对象参数。在上面的示例中,我将它传递为 nil,但您可以像您一样传递任何对象,包括 NSStrings。
      • 问题 :) - 我应该使用通知还是委托?我在建议的答案中也看到了委托。哪种方式更好?
      • 通知更好,因为这样不违反 MVC 对话规则。模型只是广播一个通知,视图控制器只是选择接收它,因为应该委托你实际上让模型弱地获得视图控制器的位置,这是一个糟糕的设计。视图控制器应该主动与模型对话,而不是相反。
      猜你喜欢
      • 2012-04-27
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 2020-01-09
      • 2014-09-10
      • 2015-05-02
      相关资源
      最近更新 更多