在数据库中使用的正确方法是什么:在异步网络呼叫中?

时间:2014-07-13 05:44:24

标签: afnetworking fmdb

当我成功地向服务器发送POST时,我正在使用AFNetworking和FMDB从数组中删除数据库行。我现在的问题是我的日志记录显示我正在跳过数组中的每一项,所以我认为我错误地将FMDB与AFNetworking的异步请求结合使用。

这就是代码的样子:

[manager POST:[_urlEndpoint absoluteString] parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
    [_dbQueue inDatabase:^(FMDatabase *db) {
        for (int i = 0; i < arrayOfIds.count; ++i)
        {
            NSLog(@"Removing event at index: %@", arrayOfIds[i]);
            [_db removeWithId:arrayOfIds[i]];
        }
    }];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

arrayOfIds中,日志显示我点击1,跳过2,点击3,跳过4等。在这种特殊情况下,我确保我只发送一个如此狭窄的POST请求根本原因所以我知道arrayOfIds没有多次访问。

我可能错过了哪些错误?

(可能)之前我刚问过的相关问题:FMDB: Does calling a method to make a query in the inDatabase block work the same way?

编辑:以下是我的日志的样子..

2014-07-13 03:08:28.684 PostTestApp[77268:6675567] Adding event to array to be sent: 1
2014-07-13 03:08:28.684 PostTestApp[77268:6675567] Adding event to array to be sent: 2
2014-07-13 03:08:28.684 PostTestApp[77268:6675567] Adding event to array to be sent: 3
2014-07-13 03:08:28.684 PostTestApp[77268:6675567] Adding event to array to be sent: 4
2014-07-13 03:08:28.684 PostTestApp[77268:6675567] Adding event to array to be sent: 5
2014-07-13 03:08:28.684 PostTestApp[77268:6675567] Adding event to array to be sent: 6
2014-07-13 03:08:29.191 PostTestApp[77268:6675567] JSON: {
    description = "Server response from /events";
    name = response;
}
2014-07-13 03:08:29.192 PostTestApp[77268:6675567] Removing event at index: 1
2014-07-13 03:08:29.192 PostTestApp[77268:6675567] Removed event from row: 1
2014-07-13 03:08:29.195 PostTestApp[77268:6675567] Removing event at index: 3
2014-07-13 03:08:29.195 PostTestApp[77268:6675567] Removed event from row: 3
2014-07-13 03:08:29.196 PostTestApp[77268:6675567] Removing event at index: 5
2014-07-13 03:08:29.197 PostTestApp[77268:6675567] Removed event from row: 5
  • "Adding event to array to be sent:"是一个for循环,用于将数据库ID添加到arrayOfIds
  • "Removing event at index:"发生在inDatabase:区块内。
  • "Removed event from row:"发生了 在removeWithId:内。

编辑2:

没有修改的完整代码块:https://gist.github.com/jonalmeida/27bee72b9015d45434e8

1 个答案:

答案 0 :(得分:1)

根据您的要点,您的实际代码如下所示:

for (int i=0; i < dbIndexArray.count; i++) {
    NSLog(@"Removing event at index: %@", dbIndexArray[i]);
    [_db removeEventWithId:[[dbIndexArray objectAtIndex:i] longLongValue]];
    [dbIndexArray removeObjectAtIndex:i];
}

问题是:在迭代数组时修改数组。删除对象0时,对象1变为对象0。

试试这个:

NSMutableArray *removedIDs = [NSMutableArray array];

for (int i=0; i < dbIndexArray.count; i++) {
    NSLog(@"Removing event at index: %@", dbIndexArray[i]);
    [_db removeEventWithId:[[dbIndexArray objectAtIndex:i] longLongValue]];
    [removedIDs addObject:dbIndexArray[i];
}

[dbIndexArray removeObjectsInArray:removedIDs];