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?
A structure that defines the name of a notification.
An object containing information broadcast to registered observers that bridges to Notification ; use NSNotification when you need reference semantics or other Foundation-specific behavior.
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.
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];
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With