ARC: __bridge versus __bridge_retained using contextInfo script

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: in line 7 you should use __bridgeeither __bridge_retained, or it doesn’t matter, or the choice depends on the value of holding the line (that is, is the line explicitly highlighted and not auto-implemented through the class initializer, for example +[NSString stringWithString:]?

+4
source share
1 answer

This is usually either

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

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

or

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

In the first case, there is no transfer of ownership, so the main program must contain a strong link for the object while the asset is active.

sheetDidEnd:. , , .

+9

All Articles