Objective-C asking for alloc on swift class

T. Benjamin Larsen picture T. Benjamin Larsen · Jun 4, 2014 · Viewed 16.1k times · Source

Some small steps to begin wrapping my head around Swift. I've basically ported an old class that simply finds the matching icon for a name and return the appropriate UIImage. The Swift part of things seems to be up and running, and looks (almost) like this:

@objc class ImageHandler{

    func iconForData(data: MyData) -> UIImage{
        let imagesAndNames = [
            "1": "tree.png",
            "2": "car.png",
            "3": "house.png",
            "7": "boat.png",
        ]

        var imageName: String? = imagesAndNames[data.imageName]
        if !imageName{
            imageName = "placeholder.png"
        }
        let icon = UIImage(named: imageName)
        return icon
    }
}

There are no warnings on the above. My old Objective-C class is however asking for an alloc method on the swift class.

ImageHandler *imageHandler = [ImageHandler alloc] init];

Returns the error "No known class method for selector 'alloc' which is true enough I guess, but how do I escape this? Will I have to base my swift-class of NSObject to avoid this?

Answer

akashivskyy picture akashivskyy · Jun 4, 2014

You declare your ImageHandler class as a root class. It doesn't have alloc method itself. You need to inherit from NSObject:

@objc class ImageHandler : NSObject {

    ...

}

Referenced from this ADF thread.