iosnsnotification

What's Difference between NSNotification 'object' and 'userInfo'?


What's difference between NSNotification's object and userInfo?

When I post a notification with a parameter, I can use object or userInfos to do it. But I do not know what the difference is between these two ways.

Is there some advantages to using userInfo? Or is using object enough?


Solution

  • The object represent the object which posted the notification. userInfo contains the additional information/data for the receiving object/function.

    According to NSNotificationCenter Class Reference:

    postNotificationName:object:userInfo:

    Creates a notification with a given name, sender, and information and posts it to the receiver.

    Declaration

    Swift

    func postNotificationName(_ notificationName: String, object notificationSender: AnyObject?, userInfo userInfo: [NSObject : AnyObject]?)
    

    Objective-C

    - (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo
    

    Parameters

    notificationName

    The name of the notification.

    notificationSender

    The object posting the notification.

    userInfo

    Information about the the notification. May be nil.

    Discussion

    This method is the preferred method for posting notifications.