gpt4 book ai didi

objective-c - Objective C 中的 Malloc 错误

转载 作者:行者123 更新时间:2023-12-03 16:49:35 26 4
gpt4 key购买 nike

现在,在我的应用程序中,有一个生产者输出一组数据;该生成器的输出(使用 XIB 文件中的“绑定(bind)”)绑定(bind)到我窗口中的 TableView 。生产者吐出数据,并显示在窗口中,一切正常。

除了我需要修改显示的数据。生产者是第三方应用程序,因此我无法直接修改它,因此我需要创建一个位于两者之间的过滤器对象。

我创建的对象如下所示:

@interface testFilter: NSObject {
id output;
}
-(void)setInput:(id)s;
@end

我更改了绑定(bind),以便生产者的输出转到我的输入:

[myFilter bind:@"input" toObject:producer withKeyPath:@"output" options:0];

我的实现如下所示:

-(id)init
{
self = [super init];
output = nil;
return self;
}

- (void)setInput:(id)newInput
{
int nEntries = (int)[newInput count];
id copiedArray = [NSMutableArray arrayWithCapacity:3];
for (id entry in newInput)
{
id copiedEntry = [entry mutableCopy];
// blah blah make some changes to copiedEntry
[copiedArray addObject:copiedEntry];
[copiedEntry release]; // I'm done with it, copiedArray added his own retain
}
[self setValue:copiedArray forKey:@"output"];

[copiedArray release]; // I'm done with it, setValue/output added a retain
}

但这会因错误而崩溃:

"malloc: *** error for object 0x108e00870: pointer being freed was not allocated"

...直到我删除 [copiedArray release] 行。

我认为我应该发送[copiedArray release]是错误的吗?

我还可以检查什么/调试此类问题的推荐方法是什么?

最佳答案

id copiedArray = [NSMutableArray arrayWithCapacity:3];

这将创建一个自动释放的对象。您不应该释放自动释放的对象。

删除您的发布调用,或将该行更改为:

id copiedArray = [[NSMutableArray alloc] initWithCapacity:3];

话虽这么说,请考虑使用 Automatic Reference Counting (ARC) .

<小时/>

来自Advanced Memory Management Programming Guide :

You own any object you create

You create an object using a method whose name begins with alloc, new, copy, or mutableCopy (for example, alloc, newObject, or mutableCopy).

You can take ownership of an object using retain

A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. You use retain in two situations: (1) In the implementation of an accessor method or an init method, to take ownership of an object you want to store as a property value; and (2) To prevent an object from being invalidated as a side-effect of some other operation.

When you no longer need it, you must relinquish ownership of an object you own

You relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object.

You must not relinquish ownership of an object you do not own

This is just corollary of the previous policy rules, stated

关于objective-c - Objective C 中的 Malloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16573804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com