4

我正在使用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 吗?

4

1 回答 1

8

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

- (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直接调用了一个完全错误的对象。我建议您阅读内存管理指南。

于 2011-10-12T14:06:39.973 回答