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?
+1
A:
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...
Jasarien
2009-06-23 14:15:09
any chance you can elaborate further? Your answer looks good but I havent the first clue how to create the required dictionary.
jdee
2009-06-23 14:23:12
Peter N Lewis' answer is an excellent example.
Jasarien
2009-06-24 14:10:55
+7
A:
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];
Peter N Lewis
2009-06-23 14:28:28
In Cocoa, you can use NSPointFromCGPoint, then use NSValue's valueWithPoint: and pointValue.
Peter Hosey
2009-06-23 16:31:29
Or you can build with NS_BUILD_32_LIKE_64 predefined, in which case NSPoint is a typedef for CGPoint (it always is in 64-bit builds).
Ahruman
2009-06-23 20:03:29