Reputation: 6068
I'm relatively new to objective-c and I've still been grasping how its runtime works. In this case, I'm unsure about whether this code is safe:
CFErrorRef errorRef;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &errorRef);
NSError * error = (NSError *)CFBridgingRelease(errorRef);
if (error != nil) {
}
Specifically, if errorRef
is not referencing anything (I'm guessing NULL
, not nil
, right?), would this cast still be safe?
Upvotes: 0
Views: 1095
Reputation: 44876
No, this code isn't safe. Per Apple's documentation:
error: On error, contains error information.
That means that it's value on success is not guaranteed. You haven't initialized the variable, either — not that I'd trust ABAddressBookCreateWithOptions
to leave it alone in success. The API documentation just doesn't guarantee that. (I suspect it would work, but this isn't the sort of thing you should rely on.)
You need to check if the function succeeded. Only if it failed should you try to access the error.
Safe code would be something like this:
CFErrorRef errorRef;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &errorRef);
if (!addressBook) {
NSError *error = (NSError *)CFBridgingRelease(errorRef);
}
Upvotes: 1