objective-c - 为什么我通过 NSNotifcationCenter 传递的值没有被保留?

标签 objective-c cocoa nsnotifications

我正在尝试通过这样的 NSNotification 发送 CGPoint

-(void)setPosition:(CGPoint)point
{ 
 NSString *pointString = NSStringFromCGPoint(point);

 NSDictionary *dict = [[NSDictionary alloc] 
                         initWithObjectsAndKeys:@"p", pointString, nil];

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

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

我已经实现了这样的观察者

-(void) init
{
    if((self = [self init])){
       [[NSNotificationCenter defaultCenter]
       addObserver:self selector:@selector(setViewPointCenter:)           
       name:@"BownceSpriteDidSetPosition" 
       object:nil];

       // I wondered wether 'object' should be something else???

       // more code etc....
    }
    return self
}

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

 NSString * val = [[notification userInfo] objectForKey:@"p"];
 CGPoint point = CGPointFromString(val);

    // trying to debug
    NSString debugString = [NSString stringWithFormat:@"YPOS -----> %f", point.y];
 NSLog(debugString);

 CGPoint centerPoint = ccp(240, 160);
 viewPoint = ccpSub(centerPoint, point);

 self.position = viewPoint;
}

但是CGPoint似乎是空的,或者可能是(0,0)。不管怎样,它都没有达到预期的效果,并且 debugString 显示 point.y 为 0.0。

从我发现的所有示例来看,我觉得我做得很好。但显然我不是。任何人都可以插入我朝正确的方向前进并指出我的错误吗?

最佳答案

你已经在字典中颠倒了你的对象和键。应该是这样的:

 NSDictionary *dict = [[NSDictionary alloc] 
                         initWithObjectsAndKeys:pointString,@"p", nil];

是的,这与您期望的方式完全相反,并且每三次创建字典时都会遇到这种情况。

关于objective-c - 为什么我通过 NSNotifcationCenter 传递的值没有被保留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1597758/

相关文章:

objective-c - 如何在游戏中心使用ios 6挑战

cocoa - 自定义绘图顶部的 NSTextField - 黑色轮廓和光标不闪烁?

iphone - 从 NSString 中删除特定字符

ios - 在IOS中从MDM服务器发送推送通知时出现推送通知错误

ios - 如何将 "move view with keyboard"函数实现到文本字段中

ios - 我可以使用类别和运行时向 UIScrollView 添加一个 BOOL 类型属性 "isScrolling"吗?

ios - 如何将.cpbitmap转换为可读图像(png,jpg,jpeg…)

iphone - 在 for 循环中追加 NSMutable 字符串

cocoa - 在 Dock 图标上方显示 NSPopover

iOS:每次 View 消失时,我是否需要从键盘事件中注销导航 Controller ?