Reputation: 2431
I have class TileMap. It initialization I load the level in memory and reads the width and height. But when I call this class with autorelease -> program crashes
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
in another class when I write:
TileMap *testmap = [[[TileMap alloc] init] autorelease];
float testg = testmap.width;
CCLOG(@"size map %0.2f", testg);
I have crash. But when I write:
TileMap *testmap = [[TileMap alloc] init];
float testg = testmap.width;
CCLOG(@"size map %0.2f", testg);
[testmap release]
I have not crash. Why is this happening?
Upvotes: 0
Views: 204
Reputation: 29767
There are several mistakes in your code. At first, you declared property as 'retain' - @property (nonatomic, retain) CCTMXTiledMap *tileMap;
and 'synthesize' it as well. It means that now you can operate with this property without any release/retain keyword. So rewrite method loadMapWithLVL
like this:
-(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;
}
One more thing - Don't call self.
in dealloc
method when you clean properties. [_tileMap release];, _titleMap = nil;
is a correct approach for cleaning memory.
Upvotes: 1