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

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

问题描述

我是目标C的新手,在使用新的ARC编译器编译代码时,我不知道如何创建和调用不带参数的方法.

I'm new to objective C, and I don't know how to create and call a method with out parameters when compiling the code with the new ARC compiler.

这是我要在非ARC目标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 * __autoreleasing *)myString {
    NSString* foo = [[NSString alloc] initWithString:@"hello"];
    *myString = foo;
}

@end

(已编辑以匹配建议).

(Edited to match suggestion).

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

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

在这里: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html

...但是我发现很难得到任何可以编译的东西,不要介意任何正确的东西.任何人都可以用适合ARC目标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目标C中的输出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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