在 Objective-C 中为类定义私有方法的最佳方法 [英] Best way to define private methods for a class in Objective-C

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

问题描述

我刚开始编写 Objective-C 并且有 Java 背景,想知道编写 Objective-C 程序的人是如何处理私有方法的.

I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods.

我了解可能存在多种约定和习惯,并将此问题视为人们在处理 Objective-C 中的私有方法时使用的最佳技术的聚合器.

I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C.

请在发布时为您的方法提供一个论据.为什么好?它有哪些(您知道的)缺点以及您如何处理它们?

Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them?

至于我目前的发现.

可以使用 categories [例如MyClass (Private)] 在 MyClass.m 文件中定义,用于对私有方法进行分组.

It is possible to use categories [e.g. MyClass (Private)] defined in MyClass.m file to group private methods.

这种方法有两个问题:

  1. Xcode(和编译器?)不会检查您是否在相应的@implementation 块中定义了私有类别中的所有方法
  2. 您必须将 @interface 声明您的私有类别放在 MyClass.m 文件的开头,否则 Xcode 会发出类似self may not respond to message privateFoo"之类的消息.

第一个问题可以通过 空类别 [例如MyClass()].
第二个让我很困扰.我希望在文件末尾附近实现(和定义)私有方法;我不知道这是否可能.

The first issue can be worked around with empty category [e.g. MyClass ()].
The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible.

推荐答案

像其他人已经说过的那样,Objective-C 中没有私有方法这样的东西.但是,从 Objective-C 2.0(即 Mac OS X Leopard、iPhone OS 2.0 及更高版本)开始,您可以创建一个名为 的空名称类别(即 @interface MyClass ())类扩展.类扩展的独特之处在于方法实现必须与公共方法位于相同的 @implementation MyClass 中.所以我这样构造我的类:

There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. @interface MyClass ()) called Class Extension. What's unique about a class extension is that the method implementations must go in the same @implementation MyClass as the public methods. So I structure my classes like this:

在 .h 文件中:

@interface MyClass {
    // My Instance Variables
}

- (void)myPublicMethod;

@end

在 .m 文件中:

@interface MyClass()

- (void)myPrivateMethod;

@end

@implementation MyClass

- (void)myPublicMethod {
    // Implementation goes here
}

- (void)myPrivateMethod {
    // Implementation goes here
}

@end

我认为这种方法的最大优点是它允许您按功能对方法实现进行分组,而不是按(有时是任意的)公共/私有区别.

I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction.

这篇关于在 Objective-C 中为类定义私有方法的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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