简体   繁体   中英

Insert a potentially null value into the sqlite database in iOS

I have a class called Content, whose URL property is nullable (URL: String?). I'd like to store this URL property in my sqlite database using FMDB, but Xcode complains I need to unwrap the optional with !

but the problem is when I do content.URL! it crashes because it's nil.

 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])

How can I successfully insert URL both when it has and does not have a value?

Thanks!

One approach that I use for cases like this is to create a class extension.

For example:

 class func databaseSafeObject(object: AnyObject?) -> AnyObject {
    if let safeObject: AnyObject = object{
        return safeObject;
    }

    return NSNull();
}

Then you can just use:

NSObject.databaseSafeObject(content.URL);

to get something that can be directly inserted in the db.

所以这最终对我有用,尽管它必须是这样看起来有点令人讨厌:

(content.URL == nil ? NSNull() : content.URL!)

There exists Swift wrappers for SQLite that may be a better fit that fmdb which can run in Swift but does not use Swift features such as optionals (that you miss here), type safety, and error handling. See for example my GRDB.swift http://github.com/groue/GRDB.swift which was heavily influenced by ccgus/fmdb.

The AnyObject type didn't work for me when working with variables of type Int and Double , so I created a similar function to handle optional Swift variables.

private func getOptionalOrNull(_ possibleValue:Any?)->Any {
  if let theValue = possibleValue {
    return theValue
  } else {
    return NSNull()
  }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM