我有TileMap类。它初始化我加载内存中的级别并读取宽度和高度。但是当我用autorelease称这个类时 - >程序崩溃
in .h
#import "cocos2d.h"
@interface TileMap : NSObject
{
CCTMXTiledMap *_tileMap;
float _width, _height;
}
@property (nonatomic, retain) CCTMXTiledMap *tileMap;
@property (readwrite) float width;
@property (readwrite) float height;
-(void) loadMapWithLVL : (NSString *)lvl;
@end
in .m
#import "TileMap.h"
@implementation TileMap
@synthesize tileMap = _tileMap;
@synthesize width = _width;
@synthesize height = _height;
- (void) dealloc
{
//[_tileMap release];
self.tileMap = nil;
[super dealloc];
}
-(void) loadMapWithLVL: (NSString *)lvl
{
[self.tileMap release];
NSString *lvl_new = [NSString stringWithFormat:@"%@.tmx",lvl];
CCLOG(@"Reload TileMap to %@", lvl_new);
self.tileMap = [[CCTMXTiledMap tiledMapWithTMXFile:lvl_new] retain];
self.width = _tileMap.mapSize.width;
self.height = _tileMap.mapSize.height;
}
- (id)init
{
self = [super init];
if (self) {
CCLOG(@"Init TileMap");
self.tileMap = [CCTMXTiledMap tiledMapWithTMXFile:@"1lvl.tmx"];
self.width = _tileMap.mapSize.width;
self.height = _tileMap.mapSize.height;
CCLOG(@"size map in init %0.2f %0.2f", _width, _height);
}
return self;
}
@end
我写的时候在另一堂课:
TileMap *testmap = [[[TileMap alloc] init] autorelease];
float testg = testmap.width;
CCLOG(@"size map %0.2f", testg);
我崩溃了。但是当我写道:
TileMap *testmap = [[TileMap alloc] init];
float testg = testmap.width;
CCLOG(@"size map %0.2f", testg);
[testmap release]
我没有崩溃。为什么会这样?
答案 0 :(得分:1)
您的代码中存在多个错误。首先,您将属性声明为“保留” - @property (nonatomic, retain) CCTMXTiledMap *tileMap;
并将其“合成”。这意味着现在您可以使用此属性进行操作,而无需任何release / retain关键字。所以重写方法loadMapWithLVL
是这样的:
-(void) loadMapWithLVL: (NSString *)lvl{
NSString *lvl_new = [NSString stringWithFormat:@"%@.tmx",lvl];
CCLOG(@"Reload TileMap to %@", lvl_new);
self.tileMap = [CCTMXTiledMap tiledMapWithTMXFile:lvl_new];
self.width = _tileMap.mapSize.width;
self.height = _tileMap.mapSize.height;
}
还有一件事 - 清理属性时,不要在self.
方法中调用dealloc
。 [_tileMap release];, _titleMap = nil;
是清理记忆的正确方法。