5

Consider this ARC code:

- (void)main {
    NSString *s = [[NSString alloc] initWithString:@"s"];
    [NSApp beginSheet:sheet 
           modalForWindow:window 
           modalDelegate:self 
           didEndSelector:@selector(sheetDidEnd:returnCode:context:) 
           contextInfo:(__bridge void *)s
    ];
}

- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode context:(void *)context {
    NSString *s = (__bridge_transfer NSString *)context;
}

Question: on line 7, should __bridge be used, or __bridge_retained, or does it not matter, or does the choice depend on the string's retain count (that is, whether the string is explicitly alloced vs being autoreleased through a class initializer like +[NSString stringWithString:]?

4

1 回答 1

11

一般来说,它是

// Object to void *:
contextInfo:(__bridge void *)s

// void * to object:
NSString *s = (__bridge NSString *)context;

或者

// Object to void *, retaining the object:
contextInfo:(__bridge_retained void *)s

// void * to object, transferring ownership.
// The object is released when s goes out of scope:
NSString *s = (__bridge_transfer NSString *)context;

在第一种情况下,没有所有权转移,因此只要工作表处于活动状态,主程序 就必须持有对该对象的强引用。

在第二种情况下,对象在创建工作表时被保留,并在sheetDidEnd:方法中释放。不需要主程序持有强引用,所以这是安全的方法。

于 2013-12-30T15:36:12.767 回答