Using NSString/parameters into SQLite statement iOS

前端 未结 2 859
旧时难觅i
旧时难觅i 2021-01-28 10:50

I have my code below. My values _emailVaue _passwordValue and _nameValue are taken from UITextFields in my app. I was under t

2条回答
  •  温柔的废话
    2021-01-28 11:32

    I'll try to explain what happened with your code and how it could be improved so that the crash would not occur. I totally agree with the usage of bound arguments, this answer is posted only as it represents an answer to how your crash can be fixed, and might help people that don't have the time to switch to bound statements.

    Here's what happened:

    1. sqlite3_prepare_v2() failed as your query string was invalid due to the fact that your strings contained the " characted
    2. due to the above, statement was either NULL or contained a garbage value
    3. sqlite3_step() crashed as an invalid pointer was passed as argument.

    Here's the fix:

    1. escape all your strings, by replacing " by \", this will generate a valid query; if you were using ' in your query, then you would have to replace ''s by \'

    Example for email:

    NSString *escapedEmail = [_emailValue stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    
    1. even if you're sure the query is correct, is still mandatory to check the result of sqlite3_prepare_v2() before using the statement in any other sqlite calls.

    As a general note, you need to code very defensively when dealing with C API's as C doesn't forgive you if you forget to check for NULL pointers. Objective-C is more soft, as it allows you to send messages to nil objects.

提交回复
热议问题