Objective-C中的私有方法和受保护方法 [英] Private and protected methods in Objective-C

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

问题描述

在Objective-C中定义私有方法和受保护方法的推荐方法是什么?一个网站建议将实现文件中的类别用于私有方法,另一个网站建议在其后加下划线或XX_,其中XX是一些特定于项目的代码.苹果本身会使用什么?

What is the recommended way to define private and protected methods in Objective-C? One website suggested using categories in the implementation file for private methods, another suggested trailing underscores, or XX_ where XX is some project-specific code. What does Apple itself use?

那受保护的方法呢?我读过的一种解决方案是在单独的文件中使用类别,例如CLASS_protected.h和CLASS_protected.m,但这似乎会使它变得肿.我该怎么办?

And what about protected methods? One solution I read was to use categories in separate files, for example CLASS_protected.h and CLASS_protected.m but this seems like it could get very bloated. What should I do?

推荐答案

存在三个问题:

  1. 隐藏在编译器中.

  1. Hiding from compiler.

也就是说,其他人无法#import一些东西并查看您的方法声明.为此,请将您的私有API放入一个单独的头文件中,在Xcode中将该头的角色标记为私有",然后将其导入您需要访问该私有API的项目中.

That is, making it impossible for someone else to #import something and see your method declarations. For that, put your private API into a separate header file, mark that header's role as "Private" in Xcode, and then import it in your project where you need access to said private API.

使用类别或类扩展来声明其他方法.

Use a category or class extension to declare the additional methods.

防止碰撞

如果要实现许多内部操作,请使用通用前缀或与Apple提供的(或第三方)提供的方法相冲突的方法,这种方法极为不可能.这对于类别尤其重要,而对于现有类的叶节点子类而言却不那么重要.

If you are implementing lots of internal goop, do so with a common prefix or something that makes a collision with Apple provided (or third party) provided methods exceedingly unlikely. This is especially critical for categories and not nearly as critical for your leaf node subclasses of existing classes.

在网站上发布链接,提示下划线,因为它们是错的,错的,错的.系统使用前导下划线标记私有API,您可以轻松地遇到冲突.

Post the link for the site suggesting leading underscores, as they are wrong, wrong, wrong. Leading underscores are used by the system to mark private API and you can run into collisions easily enough.

从运行时隐藏.

不要打扰.它只会使调试/崩溃分析变得更加困难,并且任何决心在运行时做出决定的人都将能够以任何方式入侵您的应用程序.

Don't bother. It just makes debugging / crash analysis harder and anyone determined enough to muck around at the runtime will be able to hack your app anyway.

这篇关于Objective-C中的私有方法和受保护方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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