How to perform an operation before any @synthesize'd accessor?
My model objects are lazy-loaded from an SQLite database. Don't ask why, but the code uses QuickLite to populate the objects, which means that some housek开发者_运维百科eeping has to be performed before an accessor is used the first time.
I thought, naively, that valueForKey:
and setValue:forKey:
would be called by the @synthesize
'd accessors, so that I could simply overload those 2 methods to fill the object from the db, if necessary. Unfortunately, that doesn't work: the @synthesize
'd accessors clearly don't use KVC to get/set their represented value.
My question is therefore: Is there a way to call some code before any @property
is accessed, without writing all getters/setters myself?
If your model objects were a subclass of NSManagedObject
then your accessors would be using KVC (you declare the properties, then use '@dynamic' rather than '@synthesize' in the .m file to indicate that the accessors will be taken care of by other code).
Basically it sounds like you're re-implementing the faulting behaviour in Core Data.
Based on your comment, the only way I can think of doing this would be to have a sort of proxy object which contains your actual object. So, your proxy object would have a single visible property, which is your actual object, and in the accessor for that, you would then check to see if you'd gone to the database for this particular object, if not, do your housekeeping.
So, your calls would be
NSString *someProperty = proxyObject.realObject.someProperty;
Within proxyObject, the accessor for realObject:
if (beenToTheDatabase)
return realObject;
else
{
// Do your business
beenToTheDatabase = YES;
return realObject;
}
Whether this is more or less effort than manually writing your accessors or migrating to core data, I don't know.
精彩评论