簡體   English   中英

UIImage對象意外返回null,但未返回NSData

[英]UIImage Object surprisingly returning null but not NSData

我創建了一個sqlite數據庫。

並且我在數據庫中插入了一些數據。

UIImage * imagee=[UIImage imageNamed:@"image.png"];
NSData *mydata=[NSData dataWithData:UIImagePNGRepresentation(imagee)];
const char *dbpath = [databasePath UTF8String];

NSString *insertSQL=[NSString stringWithFormat:@"insert into CONTACTS values(\"%@\",\"%@\")",@"Mathan",mydata];

NSLog(@"mydata %@",mydata);

sqlite3_stmt *addStatement;

const char *insert_stmt=[insertSQL UTF8String];
if (sqlite3_open(dbpath,&contactDB)==SQLITE_OK) {
    sqlite3_prepare_v2(contactDB,insert_stmt,-1,&addStatement,NULL);

    if (sqlite3_step(addStatement)==SQLITE_DONE) {

        sqlite3_bind_blob(addStatement,1, [mydata bytes], [mydata length], SQLITE_TRANSIENT);
        NSLog(@"Data saved");

    }
    else{

        NSLog(@"Some Error occured");
    }

    sqlite3_close(contactDB);
}
else{
    NSLog(@"Failure");
}

已經寫了一些代碼來檢索數據

sqlite3_stmt *statement;
if (sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK) {
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM contacts"];

    if (sqlite3_prepare_v2( contactDB, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW)
        {
            char *field1 = (char *) sqlite3_column_text(statement, 0);
            NSString *field1Str = [[NSString alloc] initWithUTF8String: field1];
            NSLog(@"UserName %@",field1Str);

            NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 1) length:sqlite3_column_bytes(statement, 1)];

            UIImage *newImage = [[UIImage alloc]initWithData:data];

            NSLog(@"Image OBJ %@",newImage);
            NSLog(@"Image Data  %@",data);
        }
        sqlite3_close(contactDB);
    }
}

sqlite3_finalize(statement);

問題是

在日志中,插入的NSData對象和檢索到的NSData對象是不同的(日志中的打印給出了不同的流)

此外,圖像OBJ在日志中打印為空。

在stackoverflow中已經看到了類似的問題。 但是似乎沒有什么幫助。

執行此操作時:

NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 1) length:sqlite3_column_bytes(statement, 1)];
UIImage *newImage = [[UIImage alloc]initWithData:data];

您告訴編譯器這兩個對象是不同的,因此當您打印它們時,它們將始終是不同的。 保證。 由於它們不是同一對象。

我不確定為什么newImage將顯示為null,因為您剛剛分配了對象。

您應該執行sqlite3_step sqlite3_bind_blob不前。 在插入之前,先告訴您要插入的內容!

檢查sqlite_prepare_v2sqlite3_bind_blob結果也是謹慎的。

我也建議(無關你的問題) sqlite3_finalize你之前sqlite3_close的代碼都片段。 如果有錯誤, sqlite3_errmsg可以sqlite3_errmsg生命,准確地告訴您出了什么問題,而不是猜測。

並沒有很大的區別,但是您可以嘗試一下,也可以在控制台中獲取圖像長度,以檢測圖像是否正確地響應了數據庫:

const void *ptr = sqlite3_column_blob(stmt, 1);
int size = sqlite3_column_bytes(stmt, 1);
NSLog(@"%d",size);
data = [[NSData alloc] initWithBytes:ptr length:size];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM