Search code examples
iosobjective-cormdbaccess

How do I delete multiple rows with different Ids by 'DBAccess' iOS ORM


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

I would like to delete multiple rows by specify the Ids.

Code image:

// MyDataModel is a subclass of DBObject
const int startCount = [[MyDataModel query] count];
NSLog(@"startCount:%@", @(startCount));     // startCount:21

NSString *Ids = [removeIds componentsJoinedByString:@","];
NSLog(@"removingIds:%@", Ids);              // removingIds:48,44,49,45,50,46,51,47,43

DBResultSet *rs = [[[MyDataModel query] whereWithFormat:@"Id in (%@)" withParameters:@[Ids]] fetch];
NSLog(@"resultSetCount:%@", @(rs.count));   // resultSetCount:0
[rs removeAll];

const int afterCount = [[MyDataModel query] count];
NSLog(@"afterCount:%@", @(afterCount));     // afterCount:21

Perhaps, DBAccess does not support "Id in (?,?,?)" format query?

Please tell me the solution to archive above.


[Append]

When I wrote the code as below, it worked as expected.

Is this, will be a legitimate measures?

for (NSNumber *Id in removeIds) {
    [[[[MyDataModel query] whereWithFormat:@"Id = %@" withParameters:@[Id]] fetchLightweight] removeAll];
}

[Reply to #1]

Thank you for your comment.

I tried your advice. But it could not resolved.

NSLog(@"before-delete:%@", @([[MyDataModel query] count]));
  // -> before-delete:23
if (removeIds.count) {
    NSLog(@"removeIds:%@", [removeIds componentsJoinedByString:@","]);
      // -> removeIds:119,120
    [[[[MyDataModel query] whereWithFormat:@"Id in (%@)" withParameters:removeIds] fetchLightweight] removeAll];
}
NSLog(@"after-delete:%@", @([[MyDataModel query] count]));
  // -> after-delete:22
[removeIds enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"Id[%@]=%@", obj, @([[[MyDataModel query] whereWithFormat:@"Id = %@" withParameters:@[obj]] count]));
      // -> Id[119]=0 .. 0 means succeeded to delete
      // -> Id[120]=1 .. 1 means failed to delete
}];

I want to delete Id = 119 and Id = 120, but it has deleted only one row.


It worked!

After all, I wrote the code below.

if (removeIds.count) {
    [[[[MyDataModel query] whereWithFormat:@"Id IN (%@)" withParameters:@[removeIds]] fetchLightweight] removeAll];
}

Thank you for your help!


Solution

  • DBAccess does support the 'IN (?)' style of query, and the problem is that the Id's should be passed in as an NSArray.

    NSArray* Ids = @[@(12), @(14), @(18)];
    
    DBResultSet *rs = [[[MyDataModel query] whereWithFormat:@"Id IN (%@)" withParameters:@[Ids]];
    

    or you could use in obj-c:

    DBResultSet *rs = [[[MyDataModel query] whereWithFormat:@"Id IN (%@)",Ids];