本文介绍了在Objective-C中的Swift类上调用NSStringFromClass会返回模块损坏的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道关于我们如何在Swift中获得Objective-c类的可读类名。

I am aware of this question regarding how we can get a readable class name of an objective-c class in Swift.

我想要实现的是获得从objective-c里面读取Swift类的可读类名,而不用模块修改类名。

What I want to achieve is getting the readable class name of a Swift class from inside objective-c without mangling the class name with the module.

所以如果我有一个Swift类:

So if I have a Swift class:

class Foo: NSObject{}

然后在Objective-C中我想使用方便的NSStringFromClass将类名转换为字符串。

Then inside Objective-C I would love to use the convenient NSStringFromClass to convert the class name to a string.

我希望 NSStringFromClass ([Foo class])返回 @Foo但是它返回 @Bar.Foo Bar 作为模块名称。

I would expect NSStringFromClass([Foo class]) to return @"Foo" but instead it returns @"Bar.Foo" withBarbeing the module name.

我遇到了这个但它是eems有点hacky and messy,有更好的方法吗?首选不包括手动将类名输入字符串的内容。

I came across this Gist but it seems a little hacky and messy, is there a better way? Something that doesn't include typing the class name manually into a string would be preferred.

推荐答案

在SWIFT 2.1之前:



在swift课程中输入 @objc(YourClassName)

@objc(YourClassName)

class YourClassName: NSObject {

}

您可以像这样使用NSStringFromClass:

And you can use NSStringFromClass like this:

NSStringFromClass(YourClassName.self)

它也可以从Objective-C开始工作。

It should also work from Objective-C then.

使用Swift 2.1对此答案的评论指出这已足够:

With Swift 2.1 a comment to this answer states that this is sufficient:

class YourClassName: NSObject {

}

只需使用:

var str = String(YourClassName)

我自己没有从Objective-C代码中测试过这个。

I have not tested this from Objective-C code myself though.

这篇关于在Objective-C中的Swift类上调用NSStringFromClass会返回模块损坏的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:20