To summarize what I've done:
Created a project named 2048.
Created a subclass of NSManagedObject
class BestScore: NSManagedObject { @NSManaged var bestScoreModel: BestScoreModel func update(score: Int) { self.bestScoreModel!.score = score } }
Created a subclass of NSManagedObjectModel
class BestScoreModel: NSManagedObjectModel { @NSManaged var score: Int }
Created a Data Model under Core Data tab. Named the file as 2048.xcdatamodeld. Added an entity BestScoreModel with one attribute "score" and defined the type as Integer 16. Besides, I also updated the class of the entity as 2048.BestScoreModel according to the official document.
In the controller class, I added following variables
class HomeViewController: UIViewController { var bestScore: BestScore? @lazy var context: NSManagedObjectContext = { let serviceName = NSBundle.mainBundle().infoDictionary.objectForKey("CFBundleName") as String let modelURL = NSBundle.mainBundle().URLForResource(serviceName, withExtension: "momd") let model = NSManagedObjectModel(contentsOfURL: modelURL) if model == nil { println("Error initilizing model from : \(modelURL)") abort() } let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let storeURL = (urls[urls.endIndex-1]).URLByAppendingPathComponent("\(serviceName).sqlite") var error: NSError? = nil var store = coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) if store == nil { println("Failed to load store at \(storeURL) with error: \(error?.localizedDescription)") abort() } var context = NSManagedObjectContext() context.persistentStoreCoordinator = coordinator return context }() override func viewDidLoad() { super.viewDidLoad() let entity: NSEntityDescription = NSEntityDescription.entityForName("BestScoreModel", inManagedObjectContext: context) bestScore = BestScore(entity: entity, insertIntoManagedObjectContext: context) bestScore.update(0) } }
The application was built successfully but when I ran the simulator, it threw exceptions with below
2014-07-13 00:56:59.944 2048[76600:4447122] -[NSManagedObject update:]: unrecognized selector sent to instance 0x10bc55d20
2014-07-13 00:56:59.948 2048[76600:4447122] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject update:]: unrecognized selector sent to instance 0x10bc55d20'
I'm completely new to iOS developing and have no experience before. I wanna take Swift as an opportunity for start writing apps without learning objective-c. Please let me know if I misconfigured anything.
Appreciate for your help.
PS: I get the implementation of the managed object context from here. Big thanks to the author!