将带有 NSNotificationCenter 的对象传递到其他视图

10

我正在尝试将一个对象从我的主视图类传递到另一个类中的通知接收器。

我想传递一个名为country的对象,它在主控制器中通过SOAP请求加载所有城市,我想将其发送到下一个视图中。

country = [[Country alloc] init];

Country header:

@interface Country : NSObject
{
    NSString *name;
    NSMutableArray *cities;
}

@property (nonatomic,retain) NSString *name;

- (void)addCity:(Cities *)city;
- (NSArray *)getCities;
- (int)citiesCount;    
@end

我发现使用UserInfo中的NSDictionary可以传递NSNotificatios数据。但是有没有可能直接发送整个对象而不是转换为NSDictionary呢?或者传输对象的最佳方法是什么?我一直在努力解决如何传递对象的问题。

实际上,我已经在我的应用程序中使用了这个简单的NSNotification。

主视图控制器实现中的NSNotification:

//---Call the next View---
DetailViewController *detail = [self.storyboardinstantiateViewControllerWithIdentifier:@"Detail"];
[self.navigationController pushViewController:detail animated:YES]; 

//--Transfer Data to2View 
[[NSNotificationCenter defaultCenter] postNotificationName:@"citiesListComplete" object:nil];

在两个视图控制器中实现的 NSNotification:

 // Check if MSG is RECEIVE
- (void)checkMSG:(NSNotification *)note {

    NSLog(@"Received Notification");
}

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(checkMSG:) 
                                                 name:@"citiesListComplete" object:nil];
2个回答

27

非常接近了。不过我有种感觉你可能没有理解什么是NSDictionary

请使用以下代码发布通知:

Country *country = [[[Country alloc] init] autorelease];
//Populate the country object however you want

NSDictionary *dictionary = [NSDictionary dictionaryWithObject:country forKey:@"Country"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"citiesListComplete" object:nil userInfo:dictionary];

然后像这样获取国家对象:

- (void)checkMSG:(NSNotification *)note {

    Country *country = [[note userInfo] valueForKey:@"Country"];

    NSLog(@"Received Notification - Country = %@", country);
}

你不需要将你的对象转换成NSDictionary。相反,你需要发送一个包含你的对象的NSDictionary。这允许你发送大量的信息,所有这些信息都基于NSDictionary中的键,并与你的NSNotification一起使用。


谢谢!运行得非常好。我曾经误解了NSDictionary的概念,但现在更清楚了。 - Jorge Najera T
谢谢,伙计!我一直在使用错误的方法,虽然收到了通知,但没有 userInfo。干杯! - Felipe

4

对于Swift 您可以使用以下代码传递字典

NSNotificationCenter.defaultCenter().postNotificationName(aName: String, object anObject: AnyObject?, userInfo aUserInfo: [NSObject : AnyObject]?)

例如。
NSNotificationCenter.defaultCenter().postNotificationName("OrderCancelled", object: nil, userInfo: ["success":true])

请问需要翻译成哪种语言呢?
 func updated(notification: NSNotification){

         notification.userInfo?["success"] as! Bool 
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接