2012-05-27 41 views
2

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

但是,当我的模型接收到来自服务器的消息时,它需要调用MasterViewController或DetailViewController类中的方法。我怎样才能做到这一点?

非常感谢所有帮助。

+0

什么是你的模型? MVC中的M模型? –

+0

是的,MVC中的M. – danielmhanover

回答

3

您可以从模型中触发通知,这些通知由主控和详细视图控制器处理。

在模型:

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

处理 “ReceivedData” 通知您的视图控制器(S):

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

- (void)receivedDataNotification:(id)object { 
    NSLog(@"Received Data!"); 
} 
+0

但是,如何通过NSNotifications发送字符串?似乎我所能做的就是发送一个空的通知 – danielmhanover

+0

我在上面的话题中回答了这个问题。 – diegoreymendez

+2

使用对象参数。我在上面的例子中将它传递给nil,但是你可以传入像你这样的任何对象,包括NSStrings。 – melsam

3

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

实现此目标的好方法可能是在数据更改时通过NSNotificationCenter传送NSNotification对象,并提供有关更改内容的信息,并让听众处理它。

+0

但是,如何通过NSNotifications发送字符串?似乎我所能做的只是发送一个空的通知 – danielmhanover

+1

请参阅[Apple的NSNotificationCenter文档](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class /Reference/Reference.html)。您可以使用' - (void)postNotificationName:(NSString *)notificationName对象:(id)notificationSender'来为您的通知分配名称和发件人对象。 – diegoreymendez

+0

例如,您可以让数据对象成为发件人,并且通知名称可以是一个字符串,例如:'@“senderNamePropertyChanged”'(我建议您使用常量来定义允许的通知名称)。 – diegoreymendez

2

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

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); 
}