English 中文(简体)
模型和ViewController之间的iOS通信
原标题:iOS Communication between Model and ViewController
  • 时间:2012-05-27 16:58:00
  •  标签:
  • ios

我正在开发一个基于苹果提供的主视图模板的应用程序(它由两个ViewController组成,主视图控制器和细节视图控制器)。我添加了一个模型用于与服务器通信。

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

非常感谢所有的帮助。

最佳回答

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

在模型中:

- (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!");
}
问题回答

实际上,Apple提出的MVC模式允许从模型到控制器的通知。

实现这一目标的一个好方法可能是交付NSNotification对象通过NSNotificationCenter当您的数据发生更改时,提供有关更改内容的信息,并让侦听器处理。

您应该使用可选的协议委托方法。我有一个关于如何在此PO

街区是要走的路。

您需要在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);
}




相关问题
List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code: - (...

iPhone NSUserDefaults persistance difficulty

In my app i have a bunch of data i store in the NSUserdefaults. This information consists of an NSObject (Object1) with NSStrings and NSNumbers and also 2 instances of yet another object (Object2). ...

Writing a masked image to disk as a PNG file

Basically I m downloading images off of a webserver and then caching them to the disk, but before I do so I want to mask them. I m using the masking code everyone seems to point at which can be found ...

Resize UIImage with aspect ratio?

I m using this code to resize an image on the iPhone: CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); UIGraphicsBeginImageContext(screenRect.size); [value drawInRect:screenRect blendMode:...

Allowing interaction with a UIView under another UIView

Is there a simple way of allowing interaction with a button in a UIView that lies under another UIView - where there are no actual objects from the top UIView on top of the button? For instance, ...

热门标签