如何将非托管<cfdata>转换为NSData?</cfdata>

时间:2014-08-12 10:57:17

标签: swift xcode6

我需要将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;

在斯威夫特:

var image: UIImage!

if ABPersonHasImageData(person) {
    var imgData = (ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize))
    image = UIImage.imageWithData(imgData) //Here get the error 
}

2 个答案:

答案 0 :(得分:7)

如中所述 Working with Cocoa Data Types,您必须将非托管对象转换为takeUnretainedValue()takeRetainedValue()的内存托管对象。 在你的情况下

if (ABPersonHasImageData(person)) {
    let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize).takeRetainedValue()
    let image = UIImage(data: imgData)
}

因为ABPersonCopyImageDataWithFormat()会返回一个(+1)保留值。

答案 1 :(得分:2)

if let imgData = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatOriginalSize)?.takeUnretainedValue() {
   if let image = UIImage(data: imgData) {
      //Here's your UIImage
   }
}