Objective-C asking for alloc on swift class Objective-C asking for alloc on swift class objective-c objective-c

Objective-C asking for alloc on swift class


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.


Just wanted to comment here that if you don't want to subclass NSObject or any other ObjC object, you can declare a class level initializer:

@objc class ImageHandler{    class func newInstance() -> ImageHandler {        return 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    }}

Then in ObjC

ImageHandler * imageHandler = [ImageHandler newInstance];

This way, you don't have to be dependent on ObjC Class inheritance unless you want to.


This answer is if you want to keep using pure swift objects, and do not want to inherit from NSObject. If you don't care about using pure swift objects then use akashivskyy's answer above.

I came across this same issue. I took Logan's answer and modified it so that the Objective-C caller does not have to change behavior. This is especially important if you are doing like I am and building a framework that could be consumed by Objective-C or Swift projects.

@objc public class TestClass {    public init(){}    public class func alloc() -> TestClass {return TestClass()}}

The Objective-C implementation gets to stay familiar.

TestClass *testClass = [[TestClass alloc] init];

Swift implementation stays the same as well.

let testClass = TestClass()

Edit:Furthermore I went on to implement this into an class that can be subclassed by other pure swift objects.

@objc public class ObjectiveCCompatibleObject {    required public init(){}    public class func alloc() -> Self {return self()}}