Accessing a contact detail in iOS using swift
Asked Answered
G

2

5

While using Objective-C we generally use the following code to get the details

NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);

In Swift I tried the following

var firstName : NSString = ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty).takeUnretainedValue() as NSString

and I am not able to build because of the error

Bitcast requires both operands to be pointer or neither
  %224 = bitcast %objc_object* %223 to %PSs9AnyObject_, !dbg !486
Bitcast requires both operands to be pointer or neither
  %225 = bitcast %PSs9AnyObject_ %224 to i8*, !dbg !486
LLVM ERROR: Broken function found, compilation aborted!
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 1
Galactic answered 23/7, 2014 at 4:57 Comment(0)
N
3

The following works fine in Xcode6 beta 4.

var firstName: NSString! = Unmanaged<CFString>.fromOpaque(ABRecordCopyValue(record, kABPersonFirstNameProperty).toOpaque()).takeUnretainedValue().__conversion()
Numismatics answered 28/7, 2014 at 20:22 Comment(0)
A
12

This works in Xcode 6 GM

let firstName = ABRecordCopyValue(contactRecord, kABPersonFirstNameProperty).takeRetainedValue() as String

Slightly more concise than the above example.

Andrien answered 17/9, 2014 at 7:14 Comment(3)
How do you know it is takeRetainedValue() rather than unretained. The previous answer used unretained.Minor
Couldn't find much information about this, but I assume you use takeUnretainedValue() when the pointer is to be managed by you (e.g. returned from functions with Create or Copy in their name) - this will increase their retain count by one. On the other hand you would use takeRetainedValue() when you work with results from methods with Get or similar in their name because they already have a retain count of one order to keep them alive through the life of the method.Semibreve
Update to my previous comment: Couldn't find much information about this, but I assume you use takeRetainedValue() when the pointer is to be managed by you (e.g. returned from functions with Create or Copy in their name) - this will not increase their retain count by one. On the other hand you would use takeUnretainedValue() when you work with results from methods with Get or similar in their name because they already have a retain count of zero.Semibreve
N
3

The following works fine in Xcode6 beta 4.

var firstName: NSString! = Unmanaged<CFString>.fromOpaque(ABRecordCopyValue(record, kABPersonFirstNameProperty).toOpaque()).takeUnretainedValue().__conversion()
Numismatics answered 28/7, 2014 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.