I could do this by using protocol and delegate but I would like to try with NSNotification
My task is sending an NSMutableArray
via notification from one to another view. Is it possible to do
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:myArray];
Then, in the receiver, how can I get the passed myArray. I was reading and confused about the userInfo
and object
of notification object.
Please advice me on this issue.
An NSNotification
has a property called userInfo
that is an NSDictionary
. The object
is the NSObject
that is posting the NSNotification
. So usually I use self
for the object
when I'm setting up the NSNotification
because self
is the NSObject
sending the NSNotification
. If you wish to pass an NSArray
using an NSNotification
I would do the following:
NSArray *myArray = ....;
NSDictionary *theInfo =
[NSDictionary dictionaryWithObjectsAndKeys:myArray,@"myArray", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData"
object:self
userInfo:theInfo];
And then catch it using the following:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doTheReload:)
name:@"reloadData"
object:sendingObject];
where sendingObject
is the object that is sending the NSNotification
.
Finally, decode the array in doTheReload:
using:
NSArray *theArray = [[notification userInfo] objectForKey:@"myArray"];
That always works for me. Good luck!