Pass object with NSNotificationCenter to other view

后端 未结 2 1580
栀梦
栀梦 2021-01-04 18:55

I am trying to pass an object from my main view class to other notification receiver in another class.

I want to pass an object named country, that loads all the cit

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 19:06

    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.

提交回复
热议问题