从方法返回 NSString 时的内存管理和所有权
我正在 Objective-C 中编写一个方法,该方法根据 NSMutableArray 输入返回一个字符串。我不打算让调用者修改字符串,但也不在乎。该方法当前的签名如下:
- (NSMutableString *) generateString:(NSMutableArray *)myArray
该项目目前是一个命令行基础工具,旨在了解诀窍,但这最终将出现在 iPhone 应用程序中。
我的问题是:
- 返回 NSString 会更谨慎吗?
2)返回 NSMutableString 时我应该使用 autorelease 吗?如果您建议我返回一个 NSString ,那么如何修改返回它?
3)如果我还想返回一个错误对象来标识是否发生错误,也许是一个枚举和一个字符串,在这种情况下所有权如何工作?该方法不称为 alloc、new 或 copy,那么调用者如何知道呢?除了上述方法中的字符串之外,我如何返回分配的错误对象?
谢谢!
I'm writing a method in Objective-C which is to return a string based on an NSMutableArray input. I don't intend for the callers to modify the string but couldn't care less either. The method's current signature reads as:
- (NSMutableString *) generateString:(NSMutableArray *)myArray
The project is currently a command-line Foundation Tool in order to learn the ropes but this will ultimately end up in an iPhone application.
My questions are:
- Would it be more prudent to return an NSString?
2) When returning the NSMutableString should I use autorelease? If you're recommending I return an NSString how does that modify returning it?
3) If I also want to return an error object identifying if an error occurred, perhaps an enum and a string how does ownership work in that case? The method isn't called alloc, new or copy so how would the caller know? How would I return the allocated error object in addition to the string in the above method?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSString
。它的内存占用稍小,如果调用者需要一个可变副本,只需一个方法即可创建一个:mutableCopy
。NSString
或NSMutableString
(至少如果您像示例中那样命名您的方法)! 内存管理编程指南列出了您必须遵循的规则,以避免完全混乱,并深入解释了所有内容。所以读吧!Foundation 框架使用
NSError
类来描述错误。要“返回”附加参数,您的方法将如下所示:请注意两个
**
,并且任何NSError
var 可能是NULL
而不是 < code>nil (因此您应该在方法的主体中检查这一点)。NSString
in most cases. It has a slightly smaller memory footprint and if the caller needs a mutable copy, creating one is just a method away:mutableCopy
.NSString
orNSMutableString
your method returns (at least if you name your method like in the example)! The Memory Management Programming Guide lists rules you must follow to avoid a complete mess and explains everything in-depth. So read it!The Foundation framework uses the
NSError
class to describe errors. To "return" additional parameters your method would look like this:Note the two
**
and that anyNSError
var may beNULL
and notnil
(so you should check for this in the method's body).默认情况下,方法返回 autorelease NSString,我建议使用相同的行为。如果需要修改结果字符串,可以使用临时字符串。
By default methods return autorelease NSString, and I'd recomment to use the same behaviour. If you will need to modify resulting string, you can use temporary strings.