如何制作一个真正的私有实例变量? [英] How to make a real private instance variable?

查看:106
本文介绍了如何制作一个真正的私有实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个不能从外部访问的实例变量.在objective-c中有可能发生这种情况吗?我记得苹果公司有私有变量之类的东西,但是如果人们了解它们,他们就可以使用它们.苹果称其为私有API",但是显然其他人只要知道其中有什么内容,就可以访问这些东西.

I want to make an instance variable that can't be accessed from outside. Is something like that possible in objective-c? I remember Apple has private variables and stuff like that, but if people know about them, they can use them. Apple calls that "private API", but obviously others can access that stuff if they find out what's in there.

直到现在,我相信像这样的东西会创建一个私有实例变量:

Until now I believed that something like this creates a private instance variable:

@interface MyClass : NSObject {
    CGFloat weight;
}

没有@property,没有@synthesize,只是上面的声明.

No @property, no @synthesize, just the declaration above.

我也知道Apple添加了_inFrontOfTheirPrivateInstanceVariables,但是他们说某处不希望看到其他人这样做,因为这样做可能会覆盖意外隐藏的实例变量.

Also I know Apple adds a _inFrontOfTheirPrivateInstanceVariables, but they said somewhere that they don't like to see others doing that because they might override accidently hidden instance variables when doing that.

这有什么窍门?

推荐答案

您可以在{}中使用@private关键字将所有后续变量声明设为私有.默认可见性为@protected(与Java中的protected相似),并且通常可以正常工作.您必须专门将变量声明为@public,以便在类外部直接访问该变量.

You can use the @private keyword inside the {} to make all subsequent variable declarations private. The default visibility is @protected (which is similar to protected in Java) and that generally works well. You'd have to specifically declare a variable as @public for it to be directly accessible outside the class.

This Apple documentation has further details about variable scope and visibility.

私有API"和私有变量之间也有区别.在Objective-C中,您不能将方法设为私有-任何人都可以调用任何方法.有几种创建秘密"方法的方法,但这超出了此问题的范围.以下是一些相关的SO问题:

There is also a difference between "private API" and private variables. In Objective-C, you cannot make methods private — anyone can call any method. There are several ways to create "secret" methods, but that's somewhat out of the scope of this question. Here are a few related SO questions:

  • About private instance variables in Objective-C
  • What does "@private" mean in Objective-C?
  • Is it possible to declare a method as private in Objective-C?
  • Best way to define private methods for a class in Objective-C

对于变量前面的_,请注意,Apple也为私有"方法保留了此前缀.确保避免问题的最好方法是对自己的变量和方法使用常规的命名约定.但是,除非您从Cocoa(不是NSObject)继承了某个子类,否则您将很有信心不会遇到问题.

As far as the leading _ in front of variables, be aware that Apple also reserves this prefix for "private" methods. The best way to guarantee you avoid problems is to use normal naming conventions for your own variables and methods. However, unless you subclass something from Cocoa (other than NSObject) you can be fairly confident that you won't run into problems.

这篇关于如何制作一个真正的私有实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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