什么是断言或NSAssert在实践中有好处? [英] What are assertions or NSAssert good for in practice?

查看:188
本文介绍了什么是断言或NSAssert在实践中有好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是一个好习惯,使用NSAssert所有的地方吗?这样做的好处是什么?

I wonder if it's a good habit to use NSAssert all over the place? What would be the benefit of doing that? In which situations is it a good idea to use it?

推荐答案

广泛使用 NSAssert()不会将ObjC转换成Eiffel,但它仍然是一个相当好的做法,只要你记住它是如何实际实现和它在做什么。注意 NSAssert()

Broad use of NSAssert() will not turn ObjC into Eiffel, but it's still a fairly good practice as long as you keep in mind how it's actually implemented and what it's doing. Things to keep in mind about NSAssert():

Xcode不关闭 NSAssert ()在发布模式下。您必须记住在xcconfig中将 NS_BLOCK_ASSERTIONS 添加到 GCC_PREPROCESSOR_DEFINITIONS 。 (您是使用xcconfigs ,对吗?)常见问题是在nil将静默工作的情况下断言非零;这可能意味着可以优雅恢复的事情的字段崩溃。这与 assert()使用的 NDEBUG 宏无关,如果您的代码

Xcode does not turn off NSAssert() in Release mode by default. You have to remember to add NS_BLOCK_ASSERTIONS to GCC_PREPROCESSOR_DEFINITIONS in you xcconfig. (You are using xcconfigs, right?) A common issue is to assert non-nil in cases where nil will quietly work; this can mean field crashes for things that could have gracefully recovered. This is unrelated to the NDEBUG macro used by assert(), and you have to remember to define both if your code includes both types of assertions.

如果在发布模式下编译 NSAssert()当客户向您发送他们的日志时发生问题。我自己在自己的宏中包装 NSAssert(),即使在发布模式下也是如此。

If you compile out NSAssert() in Release mode, then you get no indication where a problem happened when customers send you their logs. I personally wrap NSAssert() in my own macros that always log, even in Release mode.

NSAssert()经常强制重复的逻辑。考虑测试C ++指针为NULL的情况。您使用 NSAssert(),但您仍然需要使用一个简单的 if()测试以及避免在现场碰撞。这种重复的代码可能成为错误的源,我看到由于断言不再有效而失败的代码。 (幸运的是,这通常是在Debug模式!)我已经讨论了很多如何创建一个宏,将组合断言和 if(),但很难做没有脆弱或使代码难以理解。

NSAssert() often forces duplicated logic. Consider the case of testing a C++ pointer for NULL. You use NSAssert(), but you still need to use a simple if() test as well to avoid crashing in the field. This kind of duplicated code can become the source of bugs, and I have seen code that fails due to assertions that are no longer valid. (Luckily this is generally in Debug mode!) I have debated a lot how to create a macro that would combine the assertion and if(), but it's hard to do without being fragile or making the code hard to understand.

由于最后一个问题,我通常将 NSAssert(NO,...) code> else {} 子句中的code>,而不是在方法的顶部执行断言。这不是理想的,因为它将合同从方法签名中移开(从而降低了它的纪录利益),但它是我在实践中发现的最有效的方法。

Because of the last issue, I typically put "NSAssert(NO, ...)" in an else{} clause rather than performing assertion at the top of the method. This is not ideal because it moves the contract away from the method signature (thus reducing its documentary benefit), but it is the most effective approach I've found in practice.

这篇关于什么是断言或NSAssert在实践中有好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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