Reputation: 12070
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?
Upvotes: 5
Views: 6723
Reputation: 17811
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];
Upvotes: 15
Reputation: 58448
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...
Upvotes: 1