Question

I use ABUnknownPersonViewController to display a contact view.

I try to set an image with:

NSData *dataRef = UIImagePNGRepresentation([UIImage imageNamed:@"contact3.png"]);
ABPersonSetImageData(newPersonViewController.displayedPerson, (CFDataRef)dataRef, nil);

It doesn't work and I don't know why. Any ideas?

Was it helpful?

Solution

You can't just cast an NSData object to a CFDataRef; as noted in the docs, a CFDataRef is a "reference to an immutable CFData object", which is not the same as an NSData instance:

typedef const struct __CFData *CFDataRef;

To create the CFDataRef from the NSData instance, you need to use the CFDataCreate method, passing the bytes and length:

NSData *dataRef = UIImagePNGRepresentation([UIImage imageNamed:@"contact3.png"]); 
CFDataRef dr = CFDataCreate(NULL, [dataRef bytes], [dataRef length]);

Note also that since you create the object yourself, you must also release it, following the Core Foundation Ownership Policy; you use the CFRelease function to release ownership of the Core Foundation object:

CFRelease(dr);

This is similar to the Memory Management in Cocoa, and once the retain count of the Core Foundation object reaches zero it will be deallocated.

Edit: Stefan was completely right, in his comment, that NSData and CFData are also toll-free bridged on the iPhone with Cocoa-Touch as with Cocoa, so my original answer was wrong. My fault, should have edited it before.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top