Search code examples
swiftnsmanagedobjectswift-extensions

Swift extension on NSManagedObject


I could do this in Objective-C, but I'm having trouble figuring out how to make it work in Swift. I'm writing an extension on an NSManagedObject so that I can simply call a function any time I want to create a new entity. The function will then check the existing entities for a match, and if there isn't a match, the function will create the new entity and return it. If there is a match, it will return the match. Here's my code:

extension Chapter {
    class func createChapter(i_d: Int, team_level: Int, location: String, name: String, school: String, image: UIImage, context: NSManagedObjectContext) -> Chapter {

        var chapter : Chapter?

        var request : NSFetchRequest = NSFetchRequest(entityName: "Chapter")
        request.predicate = NSPredicate(format: "i_d = \(i_d)")
        var error : NSError?
        var results : [Chapter] = context.executeFetchRequest(request, error: &error) as [Chapter]

        if error != nil{
            println(error)
        } else if results.count == 1 {
            println("Only found one Chapter match for id: \(i_d)")
            chapter = results.first!
        } else if results.count > 1 {
            println("Found multiple Chapters for id: \(i_d)")
            for chapter in results {
                println(chapter.name)
            }
        } else {
            chapter = NSEntityDescription.insertNewObjectForEntityForName("Chapter", inManagedObjectContext: context) as? Chapter
            chapter?.i_d = i_d
            chapter?.team_level = team_level
            chapter?.location = location
            chapter?.name = name
            chapter?.school = school
            chapter?.image = UIImagePNGRepresentation(image)

            var error: NSError? = nil
            if !context.save(&error) {
                println("Saving error \(error), \(error?.userInfo)")
            } else {
                println("Saved a Chapter with id: \(i_d)")
            }
        }

        return chapter!
    }
}
  • "i_d" is a unique id for the entity

This is how I used to be able to call something like this in Objective-C (roughly translated):

Chapter *chapter = [Chapter createChapterWithID:i_d, team_level:team_level, location:location, name:name, school:school, image:image, context:context];

Whenever I try something like var chap: Chapter = Chapter.createChapter(...) , Xcode only allows me to put another Chapter object in the parameter list, whereas if I tried calling the function from a Chapter instance, the function parameters can fill in fine.

How would I go about solving my problem?

Edit:

From answer suggestions, I fixed my code by putting "class" in front of my function definition, as well as correctly creating my initial variable in the function and adding question marks in the necessary places.


Solution

  • You could try instead to create a convenience init.

    http://devmonologue.com/ios/swift/swift-initializers-designated-convenience/

    Also note, if you want to do Chapter.createChapter(), createChapter needs to be a class func, in your extension its just a regular func. So its expecting a chapter object to create the object, rather than the class.

    Change

    func createChapter ...
    

    to

    class func createChapter ...