作者:Mitchell
- 先引入一段示例代码:
- (void)viewDidLoad {
[super viewDidLoad];
//获取通讯录对象
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//获取通讯录对象汇总所有的联系人
CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
//遍历数组
CFIndex peopleCount = CFArrayGetCount(peopleArray);
for (CFIndex i = 0; i<peopleCount; i++) {
ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
CFStringRef firstname = ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
CFStringRef lastname = ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
NSString* firstName = (__bridge NSString*)firstname;
NSString* lastName = (__bridge NSString*)lastname;
NSLog(@"%@%@",firstName,lastName);
CFRelease(firstname);
CFRelease(lastname);
}
CFRelease(peopleArray);
CFRelease(addressBook);
}
- 在 iOS 中关于 CoreFoundation 框架和 Foundation 框架的桥接有三种方式。
- 1、***CoreFoundation-> Foundation ***。
将 CoreFoundation 框架的对象的对象所有权交给 Foundation 框架来使用,CoreFoundation 中的对象的内存管理还是自己来管理
- 1、***CoreFoundation-> Foundation ***。
(__bridge <#type#>)<#expression#>);
- 2、*** Foundation-> CoreFoundation ***。
将 Foundation 框架的对象 retain 之后转换为 CoreFoundation 框架来使用,这样保证了 Foundation 框架的对象被释放后,CoreFoundation 的值仍旧能正常使用:
(__bridge_retained <#CF type#>)<#expression#>;
- 3、*** CoreFoundation-> Foundation ***。
将 CoreFoundation 框架中的对象的所有权和内存都交给Foundation 框架来管理,也就是说通过这种方法来转换之后,不用写 CFRelease() 了。
(__bridge_transfer <#Objective-C type#>)<#expression#>);
- 以示例代码为例:
- (void)viewDidLoad {
[super viewDidLoad];
//获取通讯录对象
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//获取通讯录对象汇总所有的联系人
CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
//遍历数组
CFIndex peopleCount = CFArrayGetCount(peopleArray);
for (CFIndex i = 0; i<peopleCount; i++) {
ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
CFStringRef firstname = ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
CFStringRef lastname = ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
//修改firstName的转换方式
NSString* firstName = (__bridge_transfer NSString*)firstname;
NSString* lastName = (__bridge NSString*)lastname;
NSLog(@"%@%@",firstName,lastName);
//就不用写这句话了
//CFRelease(firstname);
CFRelease(lastname);
}
CFRelease(peopleArray);
CFRelease(addressBook);
}