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

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

问题描述

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

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.

防止碰撞

如果您要实现大量内部 goop,请使用通用前缀或与 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天全站免登陆