Objective-C中的私有属性和方法 [英] Private properties and methods in Objective-C

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

问题描述

在查看Apple的一个示例时,在TableViewController.m中,他们有以下内容:

In looking at one of Apple's examples, in the TableViewController.m, they have this:

// Private TableViewController properties and methods.
@interface TableViewController ()

@property (nonatomic, retain) NSMutableArray* sectionInfoArray;
@property (nonatomic, retain) NSIndexPath* pinchedIndexPath;
@property (nonatomic, assign) NSInteger openSectionIndex;
@property (nonatomic, assign) CGFloat initialPinchHeight;
... more properties and methods
@end

@implementation TableViewController
... usual stuff

我想知道为什么他们将这些属性放在.m文件中,以及它们如何是私有的.似乎任何导入TableViewController.m文件的人都可以使用这些属性和方法,对吗?为什么不在.h文件中使用@private?

I'm wondering why they put these properties in the .m file and how this is private. It seems like anyone who imports the TableViewController.m file can use these properties and methods right? Why not use the @private in the .h file?

推荐答案

他们正在做的事情是在类上声明一个类别,但是由于这是在.m文件中完成的,因此结果是这些方法是不可见的" .

What they're doing is declaring a category on the class, but since this is done in the .m file, the effect is that those methods are "invisible".

但这并不意味着不能从外部调用这些方法.这是由于在目标c中没有真正的隐私,因为我们正在处理消息,而不是方法调用.这意味着即使您不知道该对象是否实际实现了您尝试调用的方法,也可以向该对象发送消息.接收对象将在运行时确定是否可以处理此调用,甚至可以转发它,并且调用对象是否知道该方法都不会造成任何影响.

This doesn't mean however that those methods cannot be called from the outside. This is due to the fact that there is no real privacy in objective c, because we're dealing with messages, not method calls. This means you can send an object a message even if you do not know if that object actually implements the method you're trying to call. The receiving object will determine at runtime if it can handle this call, maybe it will even forward it, and it will make no difference whether the method was known to the calling object or not.

这是可以调用私有API并被拒绝的原因之一.

This is one of the reasons why it is possible to call private APIs and get rejected for it.

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

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