Pass object with NSNotificationCenter to other view

∥☆過路亽.° 提交于 2019-11-30 19:27:42

Oooooo, so close. I have a feeling you do not understand what an NSDictionary is though.

Post your notification with this:

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];

then get the country object like this:

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

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

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

You don't need to convert your object into a NSDictionary. Instead, you need to send a NSDictionary with your object. This allows you to send lots of information, all based on keys in the NSDictionary, with your NSNotification.

For Swift You can pass dictionary with using the below code

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

for example

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

And read this dictionary from

 func updated(notification: NSNotification){

         notification.userInfo?["success"] as! Bool 
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!