Last active
April 26, 2016 21:34
-
-
Save corybohon/cdb22919d49037120301d12ef15cfe37 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// DataManager.swift | |
// Reminderz | |
// | |
// Created by Cory Bohon on 4/21/16. | |
// Copyright © 2016 MartianCraft. All rights reserved. | |
// | |
import Foundation | |
class DataManager { | |
var storedTodos: Array<TodoItem> = Array() | |
class var sharedInstance: DataManager { | |
struct Static { | |
static let instance: DataManager = DataManager() | |
} | |
return Static.instance | |
} | |
init() { | |
if let data:NSData = NSUserDefaults.standardUserDefaults().objectForKey("todoItems") as? NSData { | |
self.storedTodos = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! Array<TodoItem> | |
self.saveAndNotify() | |
} | |
} | |
func addTodoItem(item: TodoItem) { | |
self.storedTodos.append(item) | |
self.saveAndNotify() | |
} | |
func removeTodoItem(item: TodoItem) { | |
if self.storedTodos.contains(item) { | |
if let indexToRemove = self.storedTodos.indexOf(item) { | |
self.storedTodos.removeAtIndex(indexToRemove) | |
self.saveAndNotify() | |
} | |
} | |
} | |
func saveAndNotify() { | |
self.storedTodos.sortInPlace { (todo1: TodoItem, todo2: TodoItem) -> Bool in | |
if todo1.todoDueDate.compare(todo2.todoDueDate) == .OrderedDescending { | |
return true | |
} | |
return false | |
} | |
let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(self.storedTodos) | |
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "todoItems") | |
NSNotificationCenter.defaultCenter().postNotificationName("dataAvailable", object: nil) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment