在 iOS 中的 sqlite 数据库中插入一个可能为空的值
Insert a potentially null value into the sqlite database in iOS
我有一个名为 Content 的 class,其 URL 属性 可以为空(URL:字符串?)。
我想使用 FMDB 将此 URL 属性 存储在我的 sqlite 数据库中,但是 Xcode 抱怨我需要使用 !
解包可选
但问题是我什么时候做 content.URL!它崩溃了,因为它是零。
success = db.executeUpdate("INSERT INTO CONTENT(ID, Icon, Title, Description, URL, IsActive) VALUES(?,?,?,?,?,?,?,?,?)", withArgumentsInArray: [content.ID, content.icon, content.title, content.description, content.URL!, content.isActive])
如何在 URL 有值和没有值时成功插入?
谢谢!
所以这最终对我有用,尽管这似乎有点令人讨厌:
(content.URL == nil ? NSNull() : content.URL!)
我在这种情况下使用的一种方法是创建 class 扩展。
例如:
class func databaseSafeObject(object: AnyObject?) -> AnyObject {
if let safeObject: AnyObject = object{
return safeObject;
}
return NSNull();
}
那么你可以使用:
NSObject.databaseSafeObject(content.URL);
获取可以直接插入数据库的东西。
SQLite 存在 Swift 包装器,它可能更适合 fmdb,它可以 运行 在 Swift 中,但不使用 Swift 功能,例如可选(你在这里错过的)、类型安全和错误处理。例如,我的 GRDB.swift http://github.com/groue/GRDB.swift 深受 ccgus/fmdb.
的影响
在处理 Int
和 Double
类型的变量时,AnyObject
类型对我不起作用,所以我创建了一个类似的函数来处理可选的 Swift变量。
private func getOptionalOrNull(_ possibleValue:Any?)->Any {
if let theValue = possibleValue {
return theValue
} else {
return NSNull()
}
}
我有一个名为 Content 的 class,其 URL 属性 可以为空(URL:字符串?)。 我想使用 FMDB 将此 URL 属性 存储在我的 sqlite 数据库中,但是 Xcode 抱怨我需要使用 !
解包可选但问题是我什么时候做 content.URL!它崩溃了,因为它是零。
success = db.executeUpdate("INSERT INTO CONTENT(ID, Icon, Title, Description, URL, IsActive) VALUES(?,?,?,?,?,?,?,?,?)", withArgumentsInArray: [content.ID, content.icon, content.title, content.description, content.URL!, content.isActive])
如何在 URL 有值和没有值时成功插入?
谢谢!
所以这最终对我有用,尽管这似乎有点令人讨厌:
(content.URL == nil ? NSNull() : content.URL!)
我在这种情况下使用的一种方法是创建 class 扩展。
例如:
class func databaseSafeObject(object: AnyObject?) -> AnyObject {
if let safeObject: AnyObject = object{
return safeObject;
}
return NSNull();
}
那么你可以使用:
NSObject.databaseSafeObject(content.URL);
获取可以直接插入数据库的东西。
SQLite 存在 Swift 包装器,它可能更适合 fmdb,它可以 运行 在 Swift 中,但不使用 Swift 功能,例如可选(你在这里错过的)、类型安全和错误处理。例如,我的 GRDB.swift http://github.com/groue/GRDB.swift 深受 ccgus/fmdb.
的影响在处理 Int
和 Double
类型的变量时,AnyObject
类型对我不起作用,所以我创建了一个类似的函数来处理可选的 Swift变量。
private func getOptionalOrNull(_ possibleValue:Any?)->Any {
if let theValue = possibleValue {
return theValue
} else {
return NSNull()
}
}