Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C asking for alloc on swift class

Tags:

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?

like image 368
T. Benjamin Larsen Avatar asked Jun 04 '14 13:06

T. Benjamin Larsen


People also ask

What does Alloc mean in Objective-C?

In its simplest form: alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable. init: short for initialization, sets up the object and returns the object.

Can we use Swift class in Objective-C?

You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.

Can Objective-C class inherit from Swift class?

Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs: You cannot subclass a Swift class in Objective-C.

What is Alloc in Swift?

This is an instance variable of the new instance that is initialized to a data structure describing the class; memory for all other instance variables is set to 0 . You must use an init... method to complete the initialization process. For example: TheClass *newObject = [[TheClass alloc] init];


1 Answers

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.

like image 93
akashivskyy Avatar answered Nov 05 '22 16:11

akashivskyy