Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotification userinfo example?

I have an array of objects that are positioned using CGPoints . At certain times in my app, an object in the array needs to notify other non-arrayed objects of its position. I understand that NSNotification is the best way to go, but I cant find a decent example of a 'sender' and 'reciever' for the notification that wraps and unwraps a CGPoint as userinfo. Can anyone help?

like image 429
jdee Avatar asked Jun 23 '09 13:06

jdee


People also ask

What is NSNotification name?

A structure that defines the name of a notification.

What is NSNotification in Swift?

An object containing information broadcast to registered observers that bridges to Notification ; use NSNotification when you need reference semantics or other Foundation-specific behavior.

What type of notification object must be used while posting distributed notifications?

A distributed notification center delivers notifications between applications. In this case, the notification object must always be a CFString object and the notification dictionary must contain only property list values.


2 Answers

In Cocoa Touch (but not Cocoa), CGPoints can be wrapped and unwrapped with

+ (NSValue *)valueWithCGPoint:(CGPoint)point
- (CGPoint)CGPointValue

NSValues can be stored in the NSDictionary passed as the userinfo parameter.

For example:

NSValue* value = [NSValue valueWithCGPoint:mypoint];
NSDictionary* dict = [NSDictionary dictionaryWithObject:value forKey:@"mypoint"];

And in your notification:

NSValue* value = [dict objectForKey:@"mypoint"];
CGPoint newpoint = [value CGPointValue];
like image 155
Peter N Lewis Avatar answered Sep 23 '22 04:09

Peter N Lewis


The userinfo object passed along with the notification is simply an NSDictionary. Probably easiest way of passing a CGPoint in the userinfo would be to wrap up the X and Y coordinates into NSNumbers using -numberWithFloat:. You can then use setObject:forKey: on the userinfo dictionary using Xpos and Ypos as the keys for example.

You could probably wrap that up into a nice category on NSMutableDictionary, with methods like setFloat:forKey or something...

like image 27
Jasarien Avatar answered Sep 20 '22 04:09

Jasarien