Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

ios - Swift: return Array of type self

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?

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 { ... }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...