Objective-C的隐藏功能 [英] Hidden features of Objective-C

查看:104
本文介绍了Objective-C的隐藏功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Apple用于Mac OS X和iPhone开发,Objective-C得到了广泛的应用。 Objective-C语言有哪些你最喜欢的隐藏功能?

Objective-C is getting wider use due to its use by Apple for Mac OS X and iPhone development. What are some of your favourite "hidden" features of the Objective-C language?


  • 每个答案有一个功能。

  • 提供该功能的示例和简短描述,而不仅仅是文档链接。

  • 使用标题作为第一行标记该功能。

推荐答案

Method Swizzling



基本上,在运行时你可以用另一种方法替换一种方法的实现。

Method Swizzling

Basically, at runtime you can swap out one implementation of a method with another.

这是一个用代码解释。

一个聪明的用例是延迟加载共享资源:通常你会实现一个 sharedFoo 方法通过获取锁,如果需要创建 foo ,获取其地址,释放锁定,然后返回 foo 。这样可以确保 foo 只创建一次,但每次后续访问都会浪费时间,而不再需要锁定。

One clever use case is for lazy loading of a shared resource: usually you would implement a sharedFoo method by acquiring a lock, creating the foo if needed, getting its address, releasing the lock, then returning the foo. This ensures that the foo is only created once, but every subsequent access wastes time with a lock that isn't needed any more.

使用方法调配,你可以像以前一样做,除非创建 foo 后,使用swizzling交换<$ c的初始实现$ c> sharedFoo 第二个没有检查,只返回我们现在知道已经创建的 foo

With method swizzling, you can do the same as before, except once the foo has been created, use swizzling to swap out the initial implementation of sharedFoo with a second one that does no checks and simply returns the foo that we now know has been created!

当然,方法调整会让你陷入困境,并且可能会出现上述例子不好的情况,但是嘿......这就是为什么它是隐藏 feature。

Of course, method swizzling can get you into trouble, and there may be situations where the above example is a bad idea, but hey... that's why it's a hidden feature.

这篇关于Objective-C的隐藏功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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