Search code examples
iphonecocoacocos2d-iphone

Cocoa: Problem passing a CGPoint with NSNotification and NSDictionary


I'm trying to fire a Notification in a method called setPosition in one class, that triggers setViewPointCenter in another class. However, I'm trying to send a CGPoint along with it. But Xcode isn't liking it one bit.

-(void)setPosition:(CGPoint)point
{   

    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"sp", point, nil];

    [[NSNotificationCenter defaultCenter] 
    postNotificationName:@"SpriteDidSetPosition" 
    object:self 
    userInfo:dict];

    [super setPosition:point];
}

Triggers this method in another class, but throws the indicated error

-(id) init{

    // Usual stuff, blah blah blah...

    [[NSNotificationCenter defaultCenter]
     addObserver:self 
     selector:@selector(setViewPointCenter:) 
     name:@"BownceSpriteDidSetPosition" 
     object:nil];

}

-(void) setViewPointCenter:(NSNotification *)notification 
{

    // ERROR: Invalid Initializer
    CGPoint point = [[notification userInfo] valueForKey:@"sp"];


    // more code here....


}

I've been digging around, and found this solution, but I still get an error.

-(void)setPosition:(CGPoint)point
{   
    // ERROR: Incompatile type for argument 1 of "Value With Point"
    NSValue *pointAsObject = [NSValue valueWithPoint:point];
    NSDictionary *dict = [[NSDictionary alloc] 
                         initWithObjectsAndKeys:@"sp", 
                         pointAsObject, 
                         nil];

    [[NSNotificationCenter defaultCenter] 
    postNotificationName:@"SpriteDidSetPosition" 
    object:self 
    userInfo:dict];

    [super setPosition:point];
}

It's driving me nuts. And to confuse me even further, changing CGPoint to NSPoint like this

-(void)setPosition:(NSPoint)point
{   

    NSValue *pointAsObject = [NSValue valueWithPoint:point];
    NSDictionary *dict = [[NSDictionary alloc] init];
    [dict initWithObjectsAndKeys:@"sp", pointAsObject, nil];

    [[NSNotificationCenter defaultCenter] 
    postNotificationName:@"SpriteDidSetPosition" 
    object:self 
    userInfo:dict];

    [super setPosition:CGPointMake(point.x, point.y)];
}

Get's rid of the error in setPosition, but I'm still screwed in setViewPointCenter. And as I understand it, CGPoint and NSPoint should equal the same thing, but it doesn't look like they do.

Does anyone have a working example of how to pass a CGPoint in a Dictionary? I can't figure it out.

This is for the iPhone, incase that makes a difference.


Solution

  • Try using +[NSValue valueWithCGPoint].