问题描述
我想编写一个类功能,它将返回类类型的数组。据我了解,我可以用自我为目标cinstanceType。我的目标是创建一个NSManagedObject与fetchObjects方法的扩展。此方法将比返回NSManagedObject子类的阵列。这里是不编译我的伪code的例子:
I would like to write a class function, which will return an array of the class type. As far as i understood, i can use "Self" for the objective-c "instanceType". My goal is to create an extension for a NSManagedObject with a fetchObjects method. This method will than return an array of NSManagedObject subclasses. Here is a example of my pseudo code which does not compile:
extension NSManagedObject {
class func fetchObjects(entity: String, context: NSManagedObjectContext, predicate: NSPredicate?, sortDescriptors: NSSortDescriptor[]?) -> Self[] {
// can't define return type of an array with type Self
// also var declaration does not work
var objects : Self[]?
return objects
}
}
任何想法我如何定义类型自数组?
Any idea how i can define an array of type Self?
感谢您的帮助!
推荐答案
这是我所使用的类似功能的JIST,请注意,这是对的NSManagedObjectContext
延期而不是 NSManagedObject
。同样的事情也很可能在 NSManagedObject
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)
请注意,您也可以实现NamedManagedObject与所有NSManagedObjects:
Note that you can also implement NamedManagedObject for all NSManagedObjects with:
extension NSManagedObject : NamedManagedObject {
class func entityName() -> String {
return NSStringFromClass(self)
}
}
如果您还保证所有的类都明确给出的Objective-C友好的名称:
If you also insure that all your classes are explicitly given Objective-C friendly names:
@objc(MyManagedObject)
class MyManagedObject : NSManagedObject { ... }
这篇关于斯威夫特:型自返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!