【发布时间】:2013-07-12 10:40:54
【问题描述】:
我正在寻找 xCode 4.5 中的内存泄漏和使用 Leaks 工具的第一步。我发现了几个问题并似乎解决了它们,但这个问题让我望而却步。
代码如下:
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
Leaks 在第二行报告泄漏,百分比在 %100 处的“i”旁边。
所以我尝试了两件事:
一,我用 autohrleas 标记了nm,如下所示:
NSString *nm = [[NSString stringWithUTF8String:img->name.c_str()] autorelease];
二,在分配给imgInfo->name 之后,我还尝试在nm 上调用release,所以代码如下所示:
imgInfo->name = nm;
[imgInfo->name retain];
[nm release];
但在这两种情况下,当我运行应用程序并调用 [imgInfo->name UTF8String] 时,应用程序都会崩溃并显示 BAD_ACCESS。
我错过了什么?
按照 Rob 的回答进行编辑:
这是 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 你会怎么做呢?
-
通过点语法或普通方法语法调用setter/getter。
标签: objective-c xcode memory-leaks