2011-10-12 52 views
3

我是新來的目標C,並且我不知道如何在使用新的ARC編譯器編譯代碼時創建和調用帶out參數的方法。在ARC中輸出參數Objective C

這是我試圖在非ARC目標C中完成的事情(這可能是錯誤的)。

// 
// 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 

(編輯以符合建議)。

我讀過這裏的文檔: http://clang.llvm.org/docs/AutomaticReferenceCounting.html

這裏: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html

...但我發現很難得到任何東西,編譯,別提什麼,是正確的。任何人都可以用適合於ARC目標C的方式重寫上面代碼的jist?

+0

究竟是什麼問題?你得到什麼編譯器錯誤? –

+0

我已經使用您的建議更新了上面的代碼示例,並且包含了一組編譯器錯誤。謝謝。 – Ben

+0

查看我的更新回答。正如編譯器所說的,你不能使用這樣的間接指針,而必須直接傳入'&a'。 –

回答

8

您需要使用的輸出參數的__autoreleasing屬性:

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

預發佈文檔(這我不能鏈接到由於NDA)放__autoreleasing兩個「中間*的,但它可能只是作爲(__autoreleasing NSString **)

您也不能使用間接雙指針(b)在您的原始代碼中。您必須使用這種形式:

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

您也是一個對象,它是完全錯誤的調用dealloc直接。我建議你閱讀內存管理指南。

+1

第一種方法有一個小錯誤。 '* myString = &foo;'應改爲'* myString = foo;'。 – diegoreymendez

+1

謝謝,修正。不知道那是怎麼回事。 –