English 中文(简体)
为什么我的价值通过没有保存的NS NotifcationCenter?
原标题:Why is my value passed through NSNotifcationCenter not preserved?
  • 时间:2009-10-20 22:56:25
  •  标签:

I m 试图通过像这样的国家安全通知发出一个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;
}

但看来,CG Point是空的,或(0,0)可能是空的。 无论是哪种方式,它都不会产生预期的效果,而辩论显示的是点。

从我发现的所有例子来看,我喜欢我这样做。 但显然我不是这样。 谁能把我推向正确的方向,指出我的错误?

最佳回答

你们的物品和钥匙在字典中倒置。 改为

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

是的,它完全落后了你期望它会走的道路,这在我每三度创建字典时就给我留下了阴影。

问题回答

你的问题是:

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

应当:

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

“目标”出现在选任人“关键”之前,因此你将贵项目列为目标A、关键目标A、目标B、关键目标B等。

你也透露了这名词典,因为你全心全意,但从未释放过(我假定你不再使用垃圾收集)。

在新的目标组合中,更好地利用:

NSDictionary *dict = @{@"p": [NSValue valueWithCGPoint:point]};

更便于使用,而不是<代码>NSValue。

取消观察员也是一个问题。 在你的法典中,你只使用<代码>。 CenterailCenter] Add Observer: Self selectedor:@selector (setView PointCenter:) name:@Bownce SpriteDidSetPosition” Object:nil];,但从来不打电话 [[NSnotation 该中心的违约中心取消观察员:自己];,whitch可以造成nas,难以解冻。 我用图书馆,防止此类坠毁。 你可以这样改写你的法典:

__weak __typeof(self) weakSelf = self;
self.observer = [AIMNotificationObserver observeName:@"BownceSpriteDidSetPosition" onChange:^(NSNotification *notification) {
   NSValue *valueOfPoint =  [notification userInfo][@"p"];
   CGPoint point = [valueOfPoint CGPointValue];
   CGPoint centerPoint = ccp(240, 160);
   viewPoint = ccpSub(centerPoint, point);
   //use weakSelf to avoid strong reference cycles
   weakSelf.position = viewPoint;
}];




相关问题
热门标签