Skip to content

Saving a Model

Jeff Hurray edited this page Apr 25, 2016 · 1 revision

Models conforming to SQLiteModel can be saved both statically and as instances.

####Static All models conforming to SQLiteModel have the static methods update and updateAll. Both take an array of Setters and an array of RelationshipSetters which are used to map values to columns and mapping tables respectively.

The following is an example of how to change every Movie's name to "New Movie"

let setters = [Movie.Title <- "New Title"]
try Movie.updateAll(setters)

update also has a Query parameter, so you can update specific rows.
The following is an example of how to update the names of movies and give them new directors if that movie made over 1 million dollars.

let jamesCameron = Person.new([Person.Name <- "James Cameron"])
let query = Movie.query.filter(Movie.Gross > 1000000)
let setters = [Movie.Title <- "New Title"]
let relationshipSetters = [Movie.Director <- jamesCameron]
try Movie.update(query, setters: setters, relationshipSetters: relationshipSetters)

Query is a type declared in SQLite.swift. More info can be found here

###Instance

All instances of model types conforming to SQLiteModel have the save method.

When any values are set for the model, a setter is created in the cache. These changes wont be reflected in the database until the save method is called, but they will still be get-able by the instance.

aNewHope.set(Movie.Title, "Episode IV: A New Hope, Remastered Edition")
let newTitle = aNewHope.get(Movie.Title) // "Episode IV: A New Hope"
// Changes not saved to DB, cache is dirty
try aNewHope.save()
// DB now has changes from above, cache is clean

Clone this wiki locally