Skip to content

Optimizing models

David Ask edited this page Mar 8, 2016 · 1 revision

By default, a Model will update all fields as defined in its persistedValuesByField property. If you want a more performant solution, you can use dirty tracking.

Start by adding a property to your model called dirtyFields:

struct Artist {
	let id: Int?
   	var name: String
   	var genre: String?
   	
   	var changedFields: [Field]? = []
   	
}

By default, this property is nil which instructs SQL to save all values. After assigning a non-nil dictionary to your model, you have to tell your model which values to update.

try artist.setNeedsSave(.Genre)

The method will throw an error if your changedFields property is nil, warning you that you have not setup dirty tracking. A convenient way of adding validations, for additional safety in your models would be to use willSet/didSet hooks on your properties.

struct Artist {
	let id: Int?
   	var name: String {
   		didSet {
   			try artist.setNeedsSave(.Name)
   		}
   	}
   	var genre: String? {
   		didSet {
   			try artist.setNeedsSave(.Genre)
   		}
   	}
   	
   	var changedFields: [Field]? = []
   	
}
Clone this wiki locally