关于桥接

iOS - 关于桥接
转载:http://www.jianshu.com/p/8993143d4d05
字数433 阅读66 评论0 喜欢1
作者:Mitchell 孟晨
作者费不少劲写的,转载请注明出处,谢谢侬。
先引入一段示例代码:

使用coreFoundation 带有Create 或者 Copy 产生的对象都有进行内存释放 CFRelease(对象名)// 桥接视情况而定;

- (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 中的对象的内存管理还是自己来管理
(__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);
}

你可能感兴趣的:(ios)