我正在通过斯坦福大学发布的精彩 iTunesU 类(class)学习 Objective-C 和 iOS 编程 ( http://www.stanford.edu/class/cs193p/cgi-bin/drupal/ )
作业 2 是创建一个带有可变按钮的计算器。命令链(例如 3+x-y)作为“anExpression”存储在 NSMutableArray 中,然后我们根据 NSDictionary 插入 x 和 y 的随机值以获得解决方案。这部分作业让我很困惑:
最后两个[方法]将表达式“转换”为属性列表或从属性列表“转换”:
+ (id)propertyListForExpression:(id)anExpression;
+ (id)expressionForPropertyList:(id)propertyList;
你会记得在讲座中,属性列表只是 NSArray、NSDictionary、NSString、NSNumber 等的任意组合,那么为什么我们还需要这个方法,因为 anExpression 已经是一个属性了列表? (由于我们构建的表达式是仅包含 NSString
和 NSNumber
对象的 NSMutableArrays
,因此它们确实已经是属性列表。)好吧,因为我们 API 的调用者不知道 anExpression 是一个属性列表。这是我们选择不向调用者公开的内部实现细节。
即便如此,您可能会认为,这两个方法的实现很容易,因为 anExpression 已经是一个属性列表,所以我们可以直接返回参数,对吗?嗯,是的,也不是。这个的内存管理有点棘手。我们将由您来解决。尽力而为。
显然,我遗漏了一些与内存管理有关的内容,因为我不明白为什么我不能直接返回传递的参数。
预先感谢您的回答!
最佳答案
考虑一下如果这样做会发生什么:
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 模式是保留
和自动释放
,因此调用者仍然不必管理内存,但对象也不需要管理内存。不要太早被摧毁:
+ (id)propertyListForExpression:(id)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/