目标C中的私人班级 [英] Private classes in Objective C

查看:81
本文介绍了目标C中的私人班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在Objective C中嵌套私有类的模式.

I would like a pattern for a nested private class in Objective C.

要求是:

  • 类将对其他类不可见/不可访问.
  • 类可以执行方法(即,不是C结构)
  • 包含的类成员对嵌套类可见/可访问

考虑到评论,我正在简化要求:

Considering the comments, I am simplifying the requirements:

  • 内部类可能被其他类访问,但不可见(类似于使用类别隐藏私有方法).
  • 内部类不必嵌套

仍然不可能吗?

推荐答案

Objective-C没有以正式声明性方式定义私有类或私有实例变量的概念.

Objective-C has no notion of private classes or private instance variables in a formal declarative fashion.

相反,Objective-C中的可见性完全由声明内容的位置控制.如果它在头文件中,则可以通过其他方式将其导入.如果在实现文件中声明了它,则不能(合理地)将其导入,因此对于该编译单元实际上是私有的.

Instead, visibility in Objective-C is entirely controlled by where you declare something. If it is in a header file, it can be imported by something else. If it is declared in an implementation file, it cannot (reasonably) be imported and, therefore, is effectively private to that compilation unit.

"it"一词几乎意味着可以声明的所有内容;类,全局等...

And by "it", I mean pretty much anything that can be declared; class, global, etc...

即如果为.m文件中的类添加了@interface/@implementation对,则该类实际上是该编译单元专用的.当然,如果没有名称空间,请确保该类的名称是唯一的.

I.e. if you stick an @interface/@implementation pair for a class in a .m file, that class is effectively private to that compilation unit. Of course, without namespaces, make sure that class is uniquely named.

考虑一下:

Foo.h:

@interface Foo: NSObject
... public interface
@end

Foo.m:

@interface __FooSupportClass: NSObject
... interface here ...
@end

@implementation __FooSupportClass
@end

@interface Foo()
@property(retain) __FooSupportClass *__fooSupport;
@end

@implementation Foo
@synthesize __fooSupport = fooSupport__;
... etc ...
@end

这为您提供了一个按可见性提供的支持类,该类仅在您的实现中可用,并且类上的实例变量和setter/getter方法在编译单元之外也不可见.

That gives you a private-by-visibility support class only available in your implementation with an instance variable and setter/getter methods on your class that are not visible outside the compilation unit either.

(请注意,Objective-C具有实例变量",而不是成员变量".它们很相似,但是最好使用该语言的词汇表.)

(Note that Objective-C has "instance variables", not "member variables". They are similar, but you'll be better off using the vocabulary of the language.)

这篇关于目标C中的私人班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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