2011-11-16 56 views
0

我有類瓷磚地圖。它初始化我加載內存中的級別,並讀取寬度和高度。但是,當我把這個類自動釋放 - >程序崩潰崩潰autorelease(cocos2d)

在.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 

在.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] 

我還沒有崩潰。這是爲什麼發生?

回答

1

代碼中有幾處錯誤。起初,你宣佈財產爲'保留' - @property (nonatomic, retain) CCTMXTiledMap *tileMap;並'綜合'它。這意味着現在您可以使用此屬性進行操作,而無需任何發佈/保留關鍵字。所以,重新編寫方法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;  
} 

一兩件事 - 不要在dealloc方法,當你清潔性能打電話self.[_tileMap release];, _titleMap = nil;是清理記憶的正確方法。