Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to pass array as obj via nsnotification

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.

like image 547
tranvutuan Avatar asked Jul 24 '12 14:07

tranvutuan


1 Answers

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!

like image 135
Justin Paulson Avatar answered Oct 22 '22 15:10

Justin Paulson