This is the jist of what I use for a similar function, note that it's an extension on NSManagedObjectContext
rather than NSManagedObject
. Something similar could probably be done on NSManagedObject
protocol NamedManagedObject {
class func entityName() -> String;
}
extension NSManagedObjectContext {
func fetchObjects<T:NSManagedObject where T:NamedManagedObject>(entity:T.Type, predicate:NSPredicate? = nil, sortDescriptors:NSSortDescriptor[]? = nil) -> T[]? {
let request = NSFetchRequest(entityName: entity.entityName())
request.predicate = predicate
request.sortDescriptors = sortDescriptors
var error:NSError? = nil
let results = self.executeFetchRequest(request, error: &error) as? T[]
assert(error == nil)
return results
}
}
extension MyObjectClass : NamedManagedObject {
class func entityName() -> String {
return "MyObjectClass"
}
}
Then using it is as simple as:
let objects = managedObjectContext.fetchObjects(MyObjectClass)
Note that you can also implement NamedManagedObject for all NSManagedObjects with:
extension NSManagedObject : NamedManagedObject {
class func entityName() -> String {
return NSStringFromClass(self)
}
}
If you also insure that all your classes are explicitly given Objective-C friendly names:
@objc(MyManagedObject)
class MyManagedObject : NSManagedObject { ... }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…