繁体   English   中英

为什么这种发行不起作用?

[英]Why this kind of release doesn't work?

我有一个关于以下方面的新手问题:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *anArray;
    anArray = [dictionary objectForKey: [NSString stringWithFormat:@"%d", section]];
    //here dictionary is of type NSDictionary, initialized in another place.
    AnObject *obj = [[AnObject alloc] init];
    obj = [anArray objectAtIndex:0];
    [anArray release];
    return obj.title;
}

如果我按原样运行,则会收到错误消息。 如果我不输入[anArray版本],则效果很好。 我不太明白为什么会这样?

谢谢。

您绝对必须阅读并理解 Cocoa内存管理规则 ,尤其是指出以下内容的基本规则:

如果使用名称以“ alloc”或“ new”开头或包含“ copy”(例如alloc,newObject或mutableCopy)的方法创建对象,或者向其发送保留消息,则您拥有该对象的所有权。 您有责任使用release或autorelease放弃您拥有的对象的所有权。 任何其他时间收到对象时,都不得释放它。

现在,看看如何掌握anArray。 您使用了方法objectForKey:它不以alloc开头,也不是new,也不包含副本。 您也没有保留anArray。 因此,您不拥有anArray。 您不得释放它。

上面引用的规则是有关在不进行垃圾回收的情况下在iPhone或Mac上使用Cocoa进行编程的最重要的知识。 这里的其他海报之一是首字母缩略词NARC(新Alloc保留副本)作为辅助备忘录,非常方便。

让我们将规则应用于代码中名为obj的变量。 您是通过调用alloc获得的,因此您有责任释放它。 但是,然后通过调用objectForIndex再次获得它(覆盖先前的值):因此在此之后,您不能释放它。 但是,第一个值确实需要释放,现在已经泄漏。 实际上,分配行是不必要的。

您不需要释放anArray,因为您没有创建它。 字典只是给您一个指向它的指针。

您这样做,似乎在创建AnObject时发生了内存泄漏。 在下一行中,将变量“ obj”重新分配为从anArray获得的变量。 但是您尚未释放在上一行创建的AnObject。

我认为您的代码应如下所示:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *anArray;
    anArray = [dictionary objectForKey: [NSString stringWithFormat:@"%d", section]];
    //here dictionary is of type NSDictionary, initialized in another place.
    obj = [anArray objectAtIndex:0];
    return obj.title;
}

您无需释放尚未创建的内容。

anArray不是由您分配,保留,复制或新增的,因此您无需释放它。

另外,您还有一个泄漏,您在其中使用alloc / init创建一个全新的AnObject实例,然后从数组中直接为其分配一个新值。

您的代码应如下所示:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *anArray;
    anArray = [dictionary objectForKey: [NSString stringWithFormat:@"%d", section]];
    //here dictionary is of type NSDictionary, initialized in another place.
    AnObject *obj = [anArray objectAtIndex:0];
    return obj.title;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM