views:

1554

answers:

2

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
any chance you can elaborate further? Your answer looks good but I havent the first clue how to create the required dictionary.
jdee
Peter N Lewis' answer is an excellent example.
Jasarien
+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
In Cocoa, you can use NSPointFromCGPoint, then use NSValue's valueWithPoint: and pointValue.
Peter Hosey
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