objective-c: writing a custom getter for ABRecordRef object
I'm trying to write a custom getter for a property with type ABRecordRef (which is a C-type). I don't understand the memory semantics of this, and I keep getting a crash whenever the property is accessed. Here's what I'm doing:
@interface Person : NSManagedObject{
...
}
@property (nonatomic) ABRecordRef abRecordPerson;
@implementation Person
@syn开发者_开发问答thesize abRecordPerson;
- (ABRecordRef) abRecordPerson
{
NSLog(@"start abRecordPerson");
ABRecordRef record = NULL;
[self willAccessValueForKey:@"abRecordPerson"];
record = [self primitiveValueForKey:@"abRecordPerson"];
[self didAccessValueForKey:@"abRecordPerson"];
if (record == NULL) {
// load record by ID
ABAddressBookRef abook = [Person getAddressBook];
record = ABAddressBookGetPersonWithRecordID(abook, [self.abGlobalID intValue]);
}
return record;
}
But when I try to access it anywhere in the same Person class with self.abRecordPerson, I get a crash (EXC_BAD_ACCESS).
Any ideas what I might be doing wrong? I'm guessing I'm doing something wrong in the memory. But this code worked if I declare the abRecordPerson as a dynamic property and added it to the Core Data model for the Person entity. Since I can't really persist the object anyways, I decided to take it out of the model, change dynamic to synthesize, and I can't get it to work from then on.
Thanks.
If this is an unmodeled property, you don't need the key-value observing calls e.g willAccessValueForKey:
, primitiveValueForKey:
and didAccessValueForKey:
.
Used to, if you called primitiveValueForKey:
on an unmodeled property, you would get the value of a random modeled property instead. I'm not sure if that still holds but it is likely the source of the problem in this case because there is no "primitive" value to access but just the value.
For an unmodeled property just use a conventional accessor something like:
if (abRecordPerson == nil) {
// load record by ID
ABAddressBookRef abook = [Person getAddressBook];
self.abRecordPerson = ABAddressBookGetPersonWithRecordID(abook, [self.abGlobalID intValue]);
}
return abRecordPerson;
In your @property
declaration, I think you need to use assign
or copy
. Maybe it is defaulting to retain
which would cause a crash with primitive types.
精彩评论