继承CCSprite时不要重写init方法,否则会无限循环
来源:互联网 发布:常见网络进攻形式 编辑:程序博客网 时间:2024/06/06 00:03
在Learn cocos2D Game Development with iOS 5一书中
第六章提到了A Common and Fatal Mistake
大概说的就是当继承CCSrpite对象的时候不要重写init方法,例如
@interface Ship : CCSprite {}+(id) ship;@implementation Ship+(id) ship{return [[[self alloc] init] autorelease];}-(id) init//这里是错误的{CCLOG(@"Ship init called ... this will repeat infinetely.");// WARNING: this will cause an infinite loop!// Reason: [super initWithFile:...] will call -(id) init which is overridden here ... repeat ad infinitum// Fix: rename this init method, for example initWithShipImage// Tip: never call anything but [super init] in your class' init method. If you call any initWith* method// then you should never do this from the -(id) init method.if ((self = [super initWithFile:@"ship.png"])){[self scheduleUpdate];}return self;}@end
正确的方式应该是这样的
-(id) initWithShipImage//这里的函数名可以随便去,就是不要与init一样{if ((self = [super initWithFile:@"ship.png"])) {[self scheduleUpdate]; } return self;}
为什么会出现这种问题你自己追踪到CCSprite源码就明白了
1。点击super initWithFile跳转到CCSprite的initWithFile方法中
源码如下
-(id) initWithFile:(NSString*)filename{NSAssert(filename!=nil, @"Invalid filename for sprite");CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage: filename];if( texture ) {CGRect rect = CGRectZero;rect.size = texture.contentSize;return [self initWithTexture:texture rect:rect];}[self release];return nil;}
2。点击self initWithTexture跳转到CCSprite的initWithTexture方法中
源码如下
-(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect{NSAssert(texture!=nil, @"Invalid texture for sprite");// IMPORTANT: [self init] and not [super init];if( (self = [self init]) ){[self setTexture:texture];[self setTextureRect:rect];}return self;}
3。注意看上面代码中if( (self = [self init]) ),
你发现OC里边比较习惯的就是用if ((self = [super init]) ),而这里却不是,这就是在继承CCSrpite后如果你重写了init方法程序就会无限循环的原因
- 继承CCSprite时不要重写init方法,否则会无限循环
- python继承和重写init方法
- python继承和重写init方法--实例
- VC最好不要重写它的init方法
- ThinkPHP中方法中的变量名不要跟方法名一致,否则查询会失败
- 在toString()方法中不要单独使用this关键字,否则会产生递归调用
- struts2 Action中方法不要以get和set开头,否则会被struts调用
- 重写 - init 方法总结
- 重写init方法
- 定义 新类 继承CCSprite ,记得重写工厂方式。
- 重写OC中的init方法
- 爱不要太深,否则会使自己受到伤害!
- 不要什么都想要,否则你会焦虑
- 不要在构造函数中调用以后会被子类重写的方法
- 继承&&方法重写
- 继承·方法重写
- 继承中的方法重写
- 继承中的方法重写
- Oracle 角色
- Oracle初学者必知的100个问题
- 编程语言排行榜-C语言依然很流行!
- Oracle中加密PL/SQL代码
- Mybatis XML 文件的学习详解
- 继承CCSprite时不要重写init方法,否则会无限循环
- 基于“请求分页”的大数量处理
- hdu 棋盘游戏(最大匹配)
- 在GDAL中以BSQ的方式保存GTiff文件
- 1287真的是刘翔的命劫吗
- 中国历史朝代歌
- VHDL学习
- VHDL学习2
- PB指定某行某列的颜色属性值uf_setcell_color