cocos2d中CCCallFuncND传参数的注意事项

来源:互联网 发布:vb中static 编辑:程序博客网 时间:2024/05/15 15:32

http://www.cnblogs.com/pengyingh/archive/2012/04/10/2439997.html

cocos2d中CCCallFuncND传参数的注意事项

A.用CCFuncBlock可以不用传参数,代码简洁高效,函数内临时变量如果不retain,不存在跳出函数使用域后被回收情况(推荐)

复制代码
//用CCCallBlock的block方式CGPoint convertedLocation = [self convertTouchToNodeSpace:touch];CCCallBlock *block = [CCCallBlock actionWithBlock:^{            //回调方法在一个函数循环内3个好处:          1.不用传递(void *)参数,所以convertedLocation不需要封装,          2.传递指针类型变量(非alloc或copy)也不需要retain,          3.alloc或copy方式产生的参数,函数内释放,省去函数外手动释放的麻烦。            [self flightBezier:convertedLocation];             }]; [flight runAction:[CCSequence actions:[CCMoveTo actionWithDuration:1 position:ccp(convertedLocation.x,convertedLocation.y)], block, nil]];
复制代码

B.使用CCFuncND传递参数(void *)类型,若想传递CGPoint等非指针类型参数,,有两种方法:

   1.传递参数地址,注意参数必须为静态变量,否则参数地址一出循环即被系统回收。

复制代码
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{  UITouch *touch = [touches anyObject];     static _startPos;     CGPoint convertedLocation = [self convertTouchToNodeSpace:touch];  _startPos = converedLocation;    //传递&_startPos     id call = [CCCallFuncND actionWithTarget:self selector:@selector(call:data:) data:(void *)&_startPos];     [flight runAction:[CCSequence actions:[CCMoveTo actionWithDuration:1 position:ccp(convertedLocation.x,convertedLocation.y)], call, nil]];     return;}
复制代码

回调:

复制代码
- (void)call:(id)sender data:(void *)point{  //sender即为flight指针    //传递&_startPos;    CGPoint p = *(CGPoint *) point;    [self flightBezier:p];}
复制代码

2.如果想传递CGPoint等非指针类型变量, 可以封装成NSValue再传递

复制代码
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{  UITouch *touch = [touches anyObject];     static _startPos;     CGPoint convertedLocation = [self convertTouchToNodeSpace:touch];  _startPos =converedLocation;    //传递nsvalue封装的cgpoint    NSValue *va = [[NSValuevalueWithCGPoint:convertedLocation]retain];//这里不能加autorease    id call1 = [CCCallFuncND actionWithTarget:self selector:@selector(call:data:) data:(void *)va];    [flight runAction:[CCSequence actions:[CCMoveTo actionWithDuration:1 position:ccp(convertedLocation.x,convertedLocation.y)], call1, nil]];return;}
复制代码

回调:

复制代码
- (void)call:(id)sender data:(void *)point{ //传递nsvalue    CGPoint p = [((NSValue *)point) CGPointValue];   //父变量,子释放,比较忌讳,但是没找到好的解决办法先凑合用    [(NSValue *)point release];    point = nil;    [self flightBezier:p];}
复制代码