0

请注意,由于此函数被传递给另一个函数,因此我无法传递 ViewController 指针。

static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
    NSString *str = @""; 

    int i;

    for(i=0; i<argc; i++)
    {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
        str = [NSString stringWithFormat:@"%@\n%s = %s\n", str, azColName[i], argv[i] ? argv[i] : "NULL"];
    }
    printf("\n");


    //tvDisplay is a UITextView
    [tvDisplay setText:str]; // <---- ??? how to get to an iVar
    return 0;
}

电话:

rc = sqlite3_exec(db, pSQL[i], callback, 0, &zErrMsg);
4

1 回答 1

2

回调函数通常有一个参数,允许您传递任意数据(通常是void *被调用的上下文或类似的东西)。您可以在设置回调函数时传入需要访问的对象,然后在回调函数中检索它:

static void myCallback(int someResult, void *context) {
   SomeClass *someObject = (SomeClass *)context;
   [someObject doStuff];
}

在您的特定情况下,“您要在回调函数中访问的任意数据”的位置是void *您当前设置为 0 的回调函数本身之后的参数:

int sqlite3_exec(
  sqlite3*,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluated */
  int (*callback)(void*,int,char**,char**),  /* Callback function */
  void *,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
);

Keep in mind that you're responsible for ensuring that any data you stick in there remains valid while the callback has not yet returned, and, if necessary, free it in the callback.

于 2012-06-29T00:31:27.067 回答