我需要将Objective-C转换为
Swift以从通讯簿中获取联系人的图像.但是我从CFData转换为NSData时遇到错误,我不知道如何使它工作.我该怎么做才能使这项工作正常进行?
在Objective-C中:
ABRecordID contactID = ABRecordGetRecordID(contactRef);
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef origContactRef = ABAddressBookGetPersonWithRecordID(addressBook,contactID);
if (ABPersonHasImageData(origContactRef)) {
NSData *imgData = (NSData*)ABPersoncopyImageDataWithFormat(origContactRef,kABPersonImageFormatOriginalSize);
img = [UIImage imageWithData: imgData];
[imgData release];
}
CFRelease(addressBook);
return img;
在Swift中:
var image: UIImage!
if ABPersonHasImageData(person) {
var imgData = (ABPersoncopyImageDataWithFormat(person,kABPersonImageFormatOriginalSize))
image = UIImage.imageWithData(imgData) //Here get the error
}
如中所述
Working with Cocoa Data Types,您必须使用takeUnretainedValue()或takeRetainedValue()将非托管对象转换为内存管理对象.
在你的情况下
Working with Cocoa Data Types,您必须使用takeUnretainedValue()或takeRetainedValue()将非托管对象转换为内存管理对象.
在你的情况下
if (ABPersonHasImageData(person)) {
let imgData = ABPersoncopyImageDataWithFormat(person,kABPersonImageFormatOriginalSize).takeRetainedValue()
let image = UIImage(data: imgData)
}
因为ABPersoncopyImageDataWithFormat()返回一个(1)保留值.