我正在尝试将一个对象从我的主视图类传递到另一个类中的其他通知接收器。
我想传递一个名为 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/