How to create a Swift object in Objective-C?

邮差的信 提交于 2019-12-22 10:54:27

问题


If you define a swift class like this

@objc class Cat {

}

In swift you can just do

var c = Cat()

But how do you make a Cat instance in Objective-C ?

Subclassing NSObject works because you can then "alloc-init" but can we achieve this without subclassing an Objective-C class?


回答1:


The most direct way is to subclass Cat from NSObject. If you can't do that, you will need to make a class method or a function that returns a Cat.

@objc class Cat {
    class func create() -> Cat {
        return Cat()
    }
}
func CreateCat() -> Cat {
    return Cat()
}


Cat *cat = [Cat create];
Cat *cat = CreateCat();



回答2:


In modern objective-c you can call functions like they were properties:

Swift:

class func create() -> Cat {
    return Cat()
}

Obj-c:

Cat *cat = Cat.create;



回答3:


You can declare +alloc in a dummy category (don't need to implement it):

@interface Cat (Alloc)
+ (instancetype)alloc;
@end

and then you can use regular alloc-init on it:

Cat *cat = [[Cat alloc] init];

all without needing to change the Swift code.



来源:https://stackoverflow.com/questions/29949127/how-to-create-a-swift-object-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!