OGeek|极客世界-中国程序员成长平台

标题: objective-c - 方法返回的对象的内存管理(iOS/Objective-C) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:44
标题: objective-c - 方法返回的对象的内存管理(iOS/Objective-C)

我正在通过斯坦福发布的 iTunesU 类(class) (http://www.stanford.edu/class/cs193p/cgi-bin/drupal/) 学习 Objective-C 和 iOS 编程

作业 2 是创建一个带有可变按钮的计算器。命令链(例如 3+x-y)作为“anExpression”存储在 NSMutableArray 中,然后我们根据 NSDictionary 将 x 和 y 的随机值子代入以获得解决方案。这部分作业让我很头疼:

最后两个 [方法] “转换” anExpression 到/从属性列表:

 + (id)propertyListForExpressionid)anExpression;
+ (id)expressionForPropertyListid)propertyList;

你会记得在讲座中,属性列表只是 NSArray、NSDictionary、NSString、NSNumber、 等的任意组合,那么为什么我们甚至需要这个方法,因为 anExpression 已经是一个属性列表? (因为我们构建的表达式是 NSMutableArrays 只包含 NSStringNSNumber 对象,它们确实已经是属性列表。)好吧,因为我们 API 的调用者不知道 anExpression 是一个属性列表。这是我们选择不向调用者公开的内部实现细节。

即便如此,你可能会想,这两个方法的实现很简单,因为 anExpression 已经是一个属性列表,所以我们可以直接返回参数,对吧?嗯,是的,也不是。这个内存管理有点棘手。我们将由您自己解决。尽力而为。

显然,我在内存管理方面遗漏了一些东西,因为我不明白为什么我不能直接返回传递的参数。

提前感谢您的任何回答!



Best Answer-推荐答案


考虑一下如果你这样做会发生什么:

NSArray *somePropertyList = [[NSArray alloc] initWithContentsOfFile"..."];
id otherPropertyList = [SomeClass propertyListForExpression:somePropertyList];
[somePropertyList release];

// 'somePropertyList' has been destroyed...
// is 'otherPropertyList' valid at this point?
[otherPropertyList writeToFile"..." atomically:YES];

因此,典型的 Objective-C 模式是 retainautorelease,因此调用者仍然不必管理内存,但对象不会不要过早地被摧毁:

+ (id)propertyListForExpressionid)expr {
    // increments the retain count by 1
    // then sets it up to be decremented at some point in the future
    // (thus balancing it out, and the caller doesn't have to do anything)
    return [[expr retain] autorelease];
}

关于objective-c - 方法返回的对象的内存管理(iOS/Objective-C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4536077/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4