【发布时间】:2013-04-09 12:04:05
【问题描述】:
我想将自定义对象分配给实例变量。
代码如下:
- MyController.h/.m
#import "CustomData.h"
@interface MyViewController : NSViewController
@property (retain) CustomData* theData;
- (void)aRandomMethod;
@end
@implementation MyViewController
@synthetize theData;
- (void)aRandomMethod {
NSData* rawData = [someOtherObject someOtherMethod];
// option 1
self.theData = [[CustomData alloc] initWithData:rawData];
// option 2
CustomData* _theData = [[Custom alloc] initWithData:rawData];
// option 3
self.theData = [[[CustomData alloc] initWithData:rawData] autorelease];
// option 4
theData = [[CustomData alloc] initWithData:rawData];
// ... later code calls some methods on theData or _theData, not useful here.
}
@end
在 Xcode 中运行分析功能时,它告诉我选项 1 和 2 存在“泄漏的对象未在稍后引用...”,但选项 3 和 4 没有。看来我需要autorelease使用 setter 时的自定义对象。我知道在方法中返回我们拥有的对象时需要使用autorelease。
你能解释一下每个选项为什么是错还是对?谢谢。
【问题讨论】:
-
您在每个选项行都缺少左大括号。
标签: objective-c macos memory-management