Опытный разработчик здесь... но несколько новичок в Swift и определенный новичок в SQLite.swift...
Я пытаюсь разобраться с использованием SQLite в приложении для iOS, поэтому я создал простое приложение, чтобы убедиться, что у меня есть основы... Все шло отлично, пока я не дошел до точки хранения и извлечения объектов данных (т.е. объекты класса)...
Вот мой код:
//**********************************************************************
//**
//** Create/Open database connection
//**
//**********************************************************************
let dbPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let db: Connection = try! Connection("\(dbPath)/stickis.sqlite3")
let dbTable = Table("testtbl")
let id = Expression<Int64>("id")
let boolfld = Expression<Bool>("boolfld")
let int64fld = Expression<Int64>("int64fld")
let stringfld = Expression<String>("stringfld")
let blobfld = Expression<SQLite.Blob?>("blobfld") // optional due to ?
//**********************************************************************
//*
//* Drop table if it exists
//*
//**********************************************************************
try! db.run(dbTable.drop(ifExists: true))
//**********************************************************************
//**
//** Create/Open Table
//**
//**********************************************************************
do
{
try db.run((dbTable.create(ifNotExists: true)
{
t in
t.column(id, primaryKey: true)
t.column(boolfld)
t.column(int64fld)
t.column(stringfld)
t.column(blobfld)
})
)
}
catch
{
print("Failed to create sticki table")
}
//**********************************************************************
//**
//** Add Record 1
//**
//**********************************************************************
do
{
let testblob: Blob = windowcontent()
let rowid = try db.run(dbTable.insert(boolfld <- true, int64fld <- 1963, stringfld <- "unknown", blobfld <- testblob))
print("inserted id: \(rowid)")
}
catch
{
print("insertion failed: \(error)")
}
//**********************************************************************
//**
//** Add Record 2
//**
//**********************************************************************
do
{
let rowid = try db.run(dbTable.insert(boolfld <- true, int64fld <- 1972, stringfld <- "David"))
print("inserted id: \(rowid)")
}
catch
{
print("insertion failed: \(error)")
}
//**********************************************************************
//**
//** Update Record 1
//**
//**********************************************************************
let rec2updt = dbTable.filter(id == 1)
do
{
if try db.run(rec2updt.update(stringfld <- "TJ")) > 0
{
print("updated to TJ")
}
else
{
print("record not found")
}
}
catch
{
print("update failed")
}
//**********************************************************************
//**
//** Query Particular Record using filter
//**
//**********************************************************************
let tjFilter = dbTable.filter(int64fld == 1964)
for dataRec in try! db.prepare(tjFilter)
{
print("id: \(dataRec[id]), stringfld: \(dataRec[stringfld])")
}
//**********************************************************************
//**
//** Query All Records
//**
//**********************************************************************
for dataRec in try! db.prepare(dbTable)
{
print("id: \(dataRec[id]), stringfld: \(dataRec[stringfld])")
}
//**********************************************************************
//**
//** Delete Records
//**
//**********************************************************************
try! db.run(dbTable.delete())
У меня все работало нормально.... пока я не добавил следующую строку в блок комментариев "Добавить запись 1"...
let testblob: Blob = windowcontent()
windowcontent() - это класс (или может быть структура), который я хочу "архивировать" и сохранить... Причина, по которой я использую Blob для его хранения, заключается в том, что сохраненный тип объекта может относиться к нескольким различным классам.
Я также пробовал это:
let testdata: Data = Data()
let testblob: Blob = testdata as Blob
и получите ожидаемую ошибку, связанную с невозможностью преобразования данных в BLOB-объекты.
Есть ли у кого-нибудь простой пример назначения и извлечения данных в/из SQLite.Blob, которым они могли бы поделиться со мной?
Кроме того, побочная тема, есть ли хорошее место, где я могу поделиться своим «базовым» примером кода iOS, когда все это будет запущено? Предполагая, что может появиться какой-нибудь другой новичок, и это может облегчить жизнь.