使用 C 数组时,我的代码似乎泄漏了,我不知道为什么。
/* LeakyClass.m */
@property (nonatomic, assign) char **array1;
@property (nonatomic, assign) id __strong *array2;
@property (nonatomic, assign) unsigned short currentDictCount;
//...
- (id)initWithCapacity:(unsigned short)capacity
{
if ((self = [super init])) {
_array1 = (char **)calloc(sizeof(char*), capacity); //Leak
_array2 = (id __strong *)calloc(sizeof(id), capacity); //Leak
}
return self;
}
- (void)dealloc {
free(_array1);
free(_array2);
_array1 = NULL;
_array2 = NULL;
}
- (void)addObjectToArray2:(id)object andCharToArray1:(char *)str
{
[self array2][[self currentDictCount]] = object;
[self array1][[self currentDictCount]] = str;
[self setCurrentDictCount:[self currentDictCount] + 1];
}
@end
我LeakyClass
用这个打电话:
/* OtherClass.m */
LeakyClass *leaky = [[LeakyClass alloc] initWithCapacity:20];
[leaky addObjectToArray2:object andCharToArray1:"1"]; // Leak
[leaky addObjectToArray2:@"example" andCharToArray1:"2"]; /Leak
[leaky addObjectToArray2:[NSURL URLWithString:exampleString] andCharToArray1:"3"]; /Leak
Instruments 指向传递给 的每个值LeakyClass
以添加到数组 1。在此示例中object
,@"example"
和[NSURL URLWithString:exampleString]
。Instruments 也指向calloc
s _array1
,_array2
但我将它们都释放在dealloc
.
我错过了什么吗?