我正在做我的第一步,在xCode 4.5中找到内存泄漏并使用Leaks工具。我发现了一些问题,似乎解决了这些问题,但是这个问题没有解决。调试目标c使用xCode泄漏的内存泄漏
下面是代码:
RUBEImageInfo* imgInfo = [[[RUBEImageInfo alloc] init] autorelease];
NSString *nm = [NSString stringWithUTF8String:img->name.c_str()];
imgInfo->name = nm;
[imgInfo->name retain]; // I'm using it outside of this method
泄漏报告在第二行中的泄漏,与旁边的百分比第“i”在100%。
所以,我想两件事情:
一个,标志着我nm
像这样autohrleas:
NSString *nm = [[NSString stringWithUTF8String:img->name.c_str()] autorelease];
两个,我也打过电话发布在nm
这是分配给imgInfo->name
使代码看起来像后这个:
imgInfo->name = nm;
[imgInfo->name retain];
[nm release];
但是在这两种情况下,当我运行它的应用程序崩溃时,并且调用[imgInfo->name UTF8String]
。
我错过了什么?以下罗布的回答
编辑:
这是RUBEImageInfo类:
#import "cocos2d.h"
@interface RUBEImageInfo : NSObject {
@public CCSprite* sprite; // the image
@public NSString* name; // the file the image was loaded from
@public class b2Body* body; // the body this image is attached to (can be NULL)
@public float scale; // a scale of 1 means the image is 1 physics unit high
@public float angle; // 'local angle' - relative to the angle of the body
@public CGPoint center; // 'local center' - relative to the position of the body
@public float opacity; // 0 - 1
@public bool flip; // horizontal flip
@public int colorTint[4]; // 0 - 255 RGBA values
}
@end
与.m:
#import "RUBEImageInfo.h"
@implementation RUBEImageInfo
// Nothing much to see here. Just make sure the body starts as NULL.
-(id)init
{
if((self=[super init])) {
body = NULL;
}
return self;
}
-(void) dealloc {
[name release];
[super dealloc];
}
@end
**永远不要用' - >'来设置或对象检索值。 **这只是摆脱了错误的做法。它很脆弱,打破了封装,而且根本不用。 – bbum
所以@bbum你会怎么做? – Eddy
通过点语法或常规方法语法调用setters/getters。 – bbum