iphone - 将带有 NSNotificationCenter 的对象传递给其他 View

标签 iphone xcode nsnotifications nsnotificationcenter

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

我想传递一个名为 Country 的对象,该对象从主 Controller 中的 SOAP 请求加载所有城市,并且我想将其发送到下一个 View 。

country = [[Country alloc] init];

国家/地区标题:

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

@property (nonatomic,retain) NSString *name;

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

我发现一种通过 NSNotificatios 传递数据的方法是在 UserInfo 中使用 NSDictionary。但是不可能发送整个对象而不是转换为 NSDictionary 吗?或者说转移的最佳方式是什么?我一直在试图弄清楚如何传递对象。

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

主视图 Controller 实现中的 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];

2View Controller 实现中的 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];

最佳答案

噢噢噢,太接近了。我有一种感觉,你不明白 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 。这允许您使用 NSNotification 发送大量信息,所有信息均基于 NSDictionary 中的键。

关于iphone - 将带有 NSNotificationCenter 的对象传递给其他 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8233416/

相关文章:

iphone - UITabBar 隐藏时留下一个白色矩形

iphone - 使用 CSS 本地文件加载 UIWebView

iphone - 将存储在 IBAction 中的值传递给下一个 Nib UITextField。

ios - 使用 flutter 构建 iOS 时 Codemagic 中的身份验证问题

iphone - 如何在 iphone 中设置选定日期的闹钟?

ios - 如何将 "move view with keyboard"函数实现到文本字段中

iphone - NSNotificationCenter 与委派(使用协议(protocol))?

ios - CallKit Framework 是否可以调用、接听和结束电话调用,或者仅用于 VOIP 调用?

iphone - 正确使用 UIRectClip 将 UIImage 缩小到图标大小

ios - 如何修改SWIFT_MODULE_NAME?