Out parameters in ARC Objective C

2019-04-11 13:21发布

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.

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

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

and here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.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?

1条回答
做个烂人
2楼-- · 2019-04-11 13:46

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

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

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:

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

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

查看更多
登录 后发表回答