保存图片的代码:
NSData *imageData=UIImagePNGRepresentation(animalImage);
NSString *insertSQL=[NSString stringWithFormat:@"insert into AnimalsTable (name,propertyID,animalID,breed,mainBreed,dateofbirth,sex,notes,imageData) values(\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\",\"%@\")",nameString,propertyString,animalidString,breedString,mainBreedString,dateString,sexString,notesString,imageData];
sqlite3_stmt *addStatement;
NSLog(@"%@",appDelegate.sqlFile);
const char *insert_stmt=[insertSQL UTF8String];
if (sqlite3_open([appDelegate.sqlFile UTF8String],&database)==SQLITE_OK) {
sqlite3_prepare_v2(database,insert_stmt,-1,&addStatement,NULL);
if (sqlite3_step(addStatement)==SQLITE_DONE) {
sqlite3_bind_blob(addStatement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
NSLog(@"Data saved");
}
else{
//NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(database));
NSLog(@"Some Error occured");
}
sqlite3_close(database);
对于检索图像:
NSString *select_sql=[NSString stringWithFormat:@"select name,animalID,imageData from AnimalsTable where mainBreed='%@' AND breed='%@'",mainString,subString];
const char *sql = [select_sql UTF8String];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
NSString *animalName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
NSString *animalid=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, 2) length: sqlite3_column_bytes(selectstmt, 2)];
[animalNamesArray addObject:animalName];
[animalIDArray addObject:animalid];
[imageDataArray addObject:dataForCachedImage];
}
}
}
else
sqlite3_close(database);
在 UITableView CellForIndexPath 中:
NSData *dataForCachedImage=[imageDataArray objectAtIndex:indexPath.row];
UIImage *dataImage=[[UIImage alloc] init];
dataImage=[UIImage imageWithData:dataForCachedImage];
cell.imageView.image=dataImage;
当我调试代码时:
我得到 NSData=226381 字节和 dataImage 0x0 的字节。
请帮我。