通过宏在 Objective-C 中进行严格的类型检查 [英] Strict Type Checking in Objective-C via Macros

查看:20
本文介绍了通过宏在 Objective-C 中进行严格的类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,在开发/调试过程中,我想确保一个对象属于某种类型:

Occasionally, during development/debugging, I want to ensure that an object is of a certain type:

PageTopBottom *newPage = [notification object];
assert([newPage isKindOfClass:[PageTopBottom class]]);

我已经研究过这个

#define assertType(_var_, _class_) assert([_var_ isKindOfClass:[_class_ class]])

PageTopBottom *newPage = (id)[notification object];
assertType(newPage, PageTopBottom);

但现在我想,如果可能的话,只使用

but now I'd like to, if possible, just use

assertType(newPage)

是否可以从变量中获取有关变量声明类型的信息?

我不确定我是否正确地构建了问题,但任何能让我能够使用一个参数断言类型的答案都会很棒.

I'm not positive that I'm framing the question correctly, but any answer that gets me to be able to assertType with one parameter would be great.

推荐答案

是否可以从变量中获取有关变量声明类型的信息?

Is it possible to get information about a variable's declared type from the variable?

没有.到程序运行时,该信息已丢失.在您的情况下, newPage 只是一个 32 或 64 位数字,它指向一个包含 Objective-C 对象的内存位.

No. By the time the program is running, that information is lost. In your case, newPage is just a 32 or 64 bit number that points to a bit of memory that holds an Objective-C object.

我认为您的原始非宏版本是正确的做法:

I think your original unmacro'd version is the right thing to do here:

assert([newPage isKindOfClass:[PageTopBottom class]]);

这完美地记录了您所做的假设,即您假设 newPage 是 PageTopBottom 或其子类之一的实例,并且对于任何了解 Objective-C 的人来说都是完全清楚的.您的宏版本稍微混淆了这一点,因为有人在代码中遇到它可能会认为它断言 newPage 是 PageTopBottom 而不是它的子类之一(我想您可以更改宏的名称以防止这种情况发生,但我只是不会打扰).

That perfectly documents the assumption you are making i.e. that you assume newPage is an instance of PageTopBottom or one of its subclasses and it's completely clear to anybody who understands Objective-C. Your macro version slightly obfuscates that, in that somebody coming across it in the code might beleive it is asserting that newPage is a PageTopBottom and not one of its subclasses (you could change the name of the macro to prevent that, I suppose, but I just wouldn't bother).

编辑

你可以做的就是将声明和断言合二为一:

What you could do is combine the declaration and assertion in one:

#define DECLARE_AND_ASSERT_IS_KIND_OF_CLASS(T, V, I)    T* V = (T*)(I); assert([(V) isKindOfClass: [(T) class])

这会像这样工作:

DECLARE_AND_ASSERT_IS_KIND_OF_CLASS(PageTopBottom, newPage, [notification object]);

这篇关于通过宏在 Objective-C 中进行严格的类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆