Using Arc can help us reduce the burden of memory management, especially for programmers who are familiar with Java.
Recently, the cfobject and nsobject conversions were encountered when obtaining the local address book. Because arc cannot manage the lifecycle of core Foundation objects, we need to use the three conversion keywords _ bridge ,__ bridge_retained and _ bridge_transfer.
In Apple's official documentation, we found:
If you cast between objective-C and core Foundation-style objects, you need to tell the compiler about the ownership semantics of the object using either a cast (defined inobjc/runtime.h
) Or a core Foundation-style macro (defined inNSObject.h
):
__bridge
Transfers a pointer between objective-C and core Foundation with no transfer of ownership.
__bridge_retained
OrCFBridgingRetain
Casts an objective-C pointer to a core Foundation pointer and also transfers ownership to you.
You are responsible for callingCFRelease
Or a related function to relinquish ownership of the object.
__bridge_transfer
OrCFBridgingRelease
Moves a non-objective-C pointer to objective-C and also transfers ownership to arc.
ARC is responsible for relinquishing ownership of the object.
_ Bridge only performs type conversion, but does not modify the object (memory) management right;
_ Bridge_retained (you can also use cfbridgingretain) to convert an objective-C object to a core Foundation object, and assign the object (memory) management right to us, cfrelease or related methods will be used to release objects in the future;
_ Bridge_transfer (cfbridgingrelease can also be used) converts the core foundation object to an objective-C object, and grants the object (memory) Management Right to arc.
For example:
- (void)logFirstNameOfPerson:(ABRecordRef)person { |
|
NSString *name = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty); |
NSLog(@"Person‘s first name: %@", name); |
[name release]; |
} |
We can make the following changes:
- (void)logFirstNameOfPerson:(ABRecordRef)person { |
|
NSString *name = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty)); |
NSLog(@"Person‘s first name: %@", name); |
} |
Objective-c Study Notes <2>