ARC Objective-C 中的输出参数
我正在使用 Objective-C,并且在使用 ARC 编译器编译代码时,我不知道如何创建和调用不带参数的方法。
这就是我试图在非 ARC Objective-C 中完成的事情(无论如何这可能是错误的)。
//
// Dummy.m
// OutParamTest
#import "Dummy.h"
@implementation Dummy
- (void) foo {
NSString* a = nil;
[self barOutString:&a];
NSLog(@"%@", a);
}
- (void) barOutString:(NSString **)myString {
NSString* foo = [[NSString alloc] initWithString:@"hello"];
*myString = foo;
}
@end
我已阅读此处的文档: https://clang.llvm.org/docs/AutomaticReferenceCounting.html
...但是我发现很难得到任何可以编译的东西,没关系任何正确的事情。有人能够以适合 ARC Objective-C 的方式重写上面代码的要点吗?
I'm using Objective-C, and I don't know how to create and call a method with out parameters when compiling the code with the ARC compiler.
This is the kind of thing I'm trying to accomplish in non-ARC Objective-C (this is probably wrong anyway).
//
// Dummy.m
// OutParamTest
#import "Dummy.h"
@implementation Dummy
- (void) foo {
NSString* a = nil;
[self barOutString:&a];
NSLog(@"%@", a);
}
- (void) barOutString:(NSString **)myString {
NSString* foo = [[NSString alloc] initWithString:@"hello"];
*myString = foo;
}
@end
I've read the documentation here:
https://clang.llvm.org/docs/AutomaticReferenceCounting.html
...but am finding it difficult to get anything that compiles, never mind anything that is correct. Would anybody be able to rewrite the jist of the code above, in a way that is suitable for ARC Objective-C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在 out 参数上使用
__autoreleasing
属性:预发布文档(由于 NDA,我不允许链接到该文档)将
__autoreleasing
放在两个 '*',但它可能只是用作(__autoreleasing NSString **)
您也不能像原始代码中那样使用间接双指针 (
b
)。您必须使用这种形式:您还直接在对象上调用dealloc,这是完全错误的。我建议您阅读内存管理指南。
You need to use the
__autoreleasing
attribute on the out parameter:The prerelease documentation (which I'm not allowed to link to due to NDA) puts the
__autoreleasing
in the middle of the two '*'s, but it might just work as(__autoreleasing NSString **)
You also cannot use an indirect double pointer (
b
) as in your original code. You must use this form:You are also calling
dealloc
directly on an object which is completely wrong. I suggest you read the memory management guidelines.