NSObject上的类别 - 保证安全 [英] Categories on NSObject -- keeping it safe

查看:161
本文介绍了NSObject上的类别 - 保证安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple已此事要说

根类的类别

类别可以向任何类添加方法,包括根类。添加到NSObject的方法可用于链接到代码的所有类。使用类别向根类添加方法有时会很有用,但它也可能非常危险。尽管看起来类别所做的修改可以很好地理解并且影响有限,但是继承给它们提供了广泛的范围。您可能正在对应用程序中看不见的类进行意外更改;你可能不知道你正在做的所有后果。此外,处理您的应用程序的其他人不知道您的更改,将无法理解他们正在做什么。

我的问题是 - 如果我选择的方法名称非常奇怪,我很确定没有人会使用它们(无论是在Apple还是在我的项目中),我还能遇到麻烦吗?还会出现意想不到的行为吗?性能影响?

My question is -- if I choose method names that are sufficiently weird that I am quite sure that no one else will use them (either at Apple or in my project), can I still get into trouble? Could there still be unexpected behavior? Performance implications?

推荐答案

如果你真的很确定Apple永远不会添加这个名称的方法,那么它是安全的。如果您希望强制确定,请在选择器名称前加上前缀。例如,Adium在一个点上添加了一个 -setObject:atIndex:方法到 NSMutableArray (是的,只是一个化妆品 现有API方法的包装器 -replaceObject:atIndex 。非常无意义... ...事实证明它与内部方法具有相同的名称,并且veeeeery略有不同的语义。这导致崩溃,但仅限于某些操作系统。如果它的名称类似于 -AISetObject:atIndex:那就没问题了。

If you're really quite certain that Apple would never add a method of that name, it's safe. If you want to enforce that certainty though, prefix the selector name. For example, Adium at one point added a -setObject:atIndex: method to NSMutableArray (yes, just a "cosmetic" wrapper over the existing API method -replaceObject:atIndex. Very pointless)... it turned out to have the same name as an internal method, and veeeeery slightly different semantics. This caused crashes, but only on certain OSs. If it had been named something like -AISetObject:atIndex:it would have been fine.

对类别的性能影响很小。我不担心这方面。

Performance implications for categories are minimal. I wouldn't worry about that aspect.

这篇关于NSObject上的类别 - 保证安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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