【问题标题】:Out parameters in ARC Objective-CARC Objective-C 中的输出参数
【发布时间】:2011-10-12 12:56:58
【问题描述】:

我用的是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

这里: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html

...但是我发现很难得到任何可以编译的东西,更不用说任何正确的东西了。任何人都能够以适合 ARC Objective-C 的方式重写上述代码的 jist 吗?

【问题讨论】:

  • 您的问题到底是什么?你得到什么编译器错误?
  • 我已根据您的建议更新了上面的代码示例,并包含了一组编译器错误。谢谢。
  • 查看我的更新答案。正如编译器所说,你不能使用这样的间接指针,而是必须直接传入&a
  • 感谢@MikeWeller 的帮助,上面的代码现在可以编译了——技术上正确吗?
  • 您不需要b 变量,只需传入&a 作为参数。您也不需要在ab 变量上使用__autoreleasing,除非您需要访问不常见的barOutString: 中的初始值。

标签: ios automatic-ref-counting autorelease


【解决方案1】:

需要在out参数上使用__autoreleasing属性:

- (void) barOutString:(NSString * __autoreleasing *)myString {
    NSString* foo = [[NSString alloc] initWithString:@"hello"];
    *myString = foo;
}

预发布文档(由于保密协议,我不允许链接到该文档)将 __autoreleasing 放在两个“*”的中间,但它可能只是作为 (__autoreleasing NSString **) 工作

您也不能像在原始代码中那样使用间接双指针 (b)。您必须使用此表格:

- (void) foo {
    NSString* a = nil;
    [self barOutString:&a];
    NSLog(@"%@", a);
}

您还直接在一个完全错误的对象上调用dealloc。我建议您阅读内存管理指南。

【讨论】:

  • 第一种方法有一个小错误。 *myString = &foo; 应更改为 *myString = foo;
  • 谢谢,已修复。不知道那是怎么进来的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2011-11-01
  • 2012-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多