let defaults = UserDefaults.standard
// String
defaults.set("Hans Mueller", forKey: "Name")
// Int
defaults.set(65, forKey: "Age")
// Date object
defaults.set(Date(), forKey: "AccessTime")
// Array
let array = ["Hello", "HdM"]
defaults.set(array, forKey: "StoredArray")
// Dictionary
let dict = ["Firstname": "Hans", "Lastname": "Mueller"]
defaults.set(dict, forKey: "StoredDict")
Reading objects will never fail but return default values if the key does not exist:
When retrieving objects, the result is optional. This means you can either accept the optionality, or typecast it to a non-optional type and use the nil coalescing operator to handle missing values. For example object(forKey:)
returns AnyObject?
so you need to conditionally typecast it to your data type:
let savedArray = defaults.object(forKey: "SavedArray") as? [String] ?? [String]()
let path = Bundle.main.path(forResource: "myprop", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
// reading a String item
let tableData = dict!.object(forKey: "testitem") as! String
// reading an Array of Strings
let devices = dict!.object(forKey: "devices") as! [String]
// load the property file
let writableProp = NSMutableDictionary(contentsOfFile: path!)
// change a value
writableProp?.setValue("Ansgar Gerlicher", forKey: "Name")
// write the property file atomically
writableProp?.write(toFile: path!, atomically: true)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let container = appDelegate.persistentContainer
let context = container.viewContext
let person = Person(context: context)
person.name = "Ansgar R. S. Gerlicher"
person.age = 22
save()
on the context:do {
try context.save()
} catch {
print("Failed saving context")
}
fetch()
function to load the objects from the storelet request : NSFetchRequest<Person> = Person.fetchRequest()
do {
let result = try context.fetch(request)
for personObject in result {
print(personObject)
}
} catch {
print("Loading Person failed")
}