ARC Objective-C中的输出参数 [英] Out parameters in ARC Objective-C

查看:71
本文介绍了ARC Objective-C中的输出参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Objective-C,并且在使用ARC编译器编译代码时,我不知道如何创建和调用不带参数的方法.

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.

这是我试图在非ARC Objective-C中完成的事情(无论如何这可能是错误的.)

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

我在这里阅读了文档: https://clang.llvm.org/docs/AutomaticReferenceCounting.html

I've read the documentation here: https://clang.llvm.org/docs/AutomaticReferenceCounting.html

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

...但是我发现很难得到任何可以编译的东西,不要介意任何正确的东西.任何人都可以采用适合ARC Objective-C的方式重写上述代码的内容吗?

...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?

推荐答案

您需要在out参数上使用 __ autoreleasing 属性:

You need to use the __autoreleasing attribute on the out parameter:

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

预发行版文档(由于NDA而不能链接到该文档)将 __ autoreleasing 放在两个'*'的中间,但它可能只是作为(__autoreleasing NSString **)

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 **)

您也不能像原始代码中那样使用间接双指针( b ).您必须使用以下形式:

You also cannot use an indirect double pointer (b) as in your original code. You must use this form:

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

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

You are also calling dealloc directly on an object which is completely wrong. I suggest you read the memory management guidelines.

这篇关于ARC Objective-C中的输出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆