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

查看:76
本文介绍了通过宏在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)

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

我不能肯定我正确地提出了问题,但是任何使我能够使用一个参数来断言Type的答案都是很好的.

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天全站免登陆