Search code examples
iosobjective-cormdbaccess

How do I perform event trigger operations with 'DBAccess' iOS ORM


I am using DBAccess framework v1.6.12 with Xcode 7.1.1.

I would like to use an event trigger when INSERT, UPDATE or DELETE the rows like :

  1. Existing specific period data's 'longest' parameter turn into 'NO'.
  2. Find the row which has the longest 'text'.
  3. Change its row's 'longest' parameter to 'YES'.

Code image:

@interface NoteModel : DBObject
@property uint32_t dateYMD; // not unique
@property BOOL longest; // default value is NO
@property NSString *text;
@end

- (void)test {
    NoteModel *obj = [NoteModel new];
    obj.dateYMD = 20151201;
    obj.text = @"hoge";
    [obj commit]; //< HERE I want to fire the event trigger
}

DBObject#entityWillInsert is just return BOOL value without chaging infos.


Solution

  • To intercept events as you want you would use the following methods:

    - (BOOL)entityWillInsert;
    - (BOOL)entityWillUpdate;
    - (BOOL)entityWillDelete;
    - (void)entityDidInsert;
    - (void)entityDidUpdate;
    - (void)entityDidDelete;
    

    From your example, although I might not be exactly clear with what you are asking, I would use the entityWillInsert/Update methods to query for other objects that may be longer and then you can update the longest flag accordingly.

    In semi-psuedo code it would look something like this:

    - (BOOL)entityWillInsert {
    
        // see if we have any existing records with a longer text field
        self.longest = [[[NoteModel query] whereWithFormat:@"length(text) > length(%@)", self.text] count] ? NO:YES;
    
        // now if this is to be the longest then we will need to ensure that the current record is updated too.
        if(self.longest) { 
           for (NoteModel* r in [[[NoteModel query] where:@"longest = 1"] fetch]) {
                r.longest = NO;
               [r commit];
           }
        }
    
        // you must return yes to ensure the ORM knows to complete the action
        return YES;
    
    }