In Xcode, when I create a new file extends NSManagedObjectContext class, add methods in this extension file, compile the project and there is no problem.
NSManagedObjectContext+BaseModel.swift
import Foundation
import CoreData
import CoreDataStack
extension NSManagedObjectContext {
public func insertObject<T: NSManagedObject>() -> T {
guard let object = NSEntityDescription.insertNewObjectForEntityForName(T.modelName(), inManagedObjectContext: self) as? T
else {
fatalError("Invalid Core Data Model")
}
return object
}
}
However, when I use it in the ViewController.swift, like context.insertObject()
, the compiler reports an error saying:
Value of type 'NSManagedObjectContext' has no member 'insertObject'
After searching in StackOverflow, I found a post "Using extensions in separate .swift file". As the post author said, the above problem disappeared when I put the extension NSManagedObjectContext
code in my custom CoreDataStack.swift. But why?? Should not extension Apple's class be in a separate file??