The answer to 0x7fffffff is correct, but to improve the Apple pattern code, you can catch a specific error in the catch block with catch let error as NSError as follows:
func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch let error as NSError { NSLog("Unresolved error \(error), \(error.userInfo)")
The best practice is to use var error , the witch will still be available if you just use it like this:
func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { NSLog("Unresolved error \(error), \(error.userInfo)")
In the same way, if you are sure that managedObjectContext.save() will not throw a exception , the code will be reduced to:
func saveContext () { if managedObjectContext.hasChanges { try! managedObjectContext.save() } }
And to extrapolate to why managedObjectContext is not optional in Swift 2 code, this is because NSManagedObject(concurrencyType:) is an initializer that does not interrupt. In Xcode 6, the template code returned an optional context if NSPersistentStoreCoordinator is zero, but you can easily handle this by checking.
lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var moc = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) moc.persistentStoreCoordinator = coordinator return moc }()
Ian Jun 09 '15 at 2:48 2015-06-09 14:48
source share