简体   繁体   中英

iOS: About CF object and objective-c object retain count

I have tested 3 codes below under ARC :

1、readStream.retainCount = 2;

       @property(nonatomic, strong) NSInputStream *readStream;

        CFReadStreamRef ref = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request);
        [self setReadStream:(__bridge NSInputStream *)(ref)];
        CFRelease(ref);

2、readStream.retainCount = 3;

        [self setReadStream:(__bridge NSInputStream *)(CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request))];

3、readStream.retainCount = 3;

[self setReadStream:CFBridgingRelease(CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request))];

My question is: Why 1 is different from 2&3 ? Which usage is correct ? And is the readStream should be strong property?

From the docs :

__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.

__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.

This means that both approaches are valid. Basically what it says is that if you use CFBridgingRelease you should not use CFRelease because you transfer the ownership, that's why you see an increase in the retainCount, although, as 'Kevin' pointed out, in ARC that's meaningless.

Regarding the second question, your readStream variable can be strong or not. There's no special consideration here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM