xcode 如何将财产私有化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6998177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make properties private?
提问by Randall
Someone told me I could make properties private so that only an instance of the class can refer to them (via self.)
有人告诉我我可以将属性设为私有,以便只有类的实例可以引用它们(通过 self.)。
However, if I use @private in the class interface and then declare the property normally, it can still be accessed from outside of the class... So how can I make properties private? Syntax example please.
但是,如果我在类接口中使用@private,然后正常声明属性,仍然可以从类外部访问它......那么我如何将属性设为私有?请语法示例。
回答by dtuckernet
You need to include these properties in a class extension. This allows you to define properties (and more recently iVars) within your implementation file in an interface declaration. It is similar to defining a category but without a name between the parentheses.
您需要在类扩展中包含这些属性。这允许您在接口声明中的实现文件中定义属性(以及最近的 iVars)。它类似于定义一个类别,但在括号之间没有名称。
So if this is your MyClass.m file:
因此,如果这是您的 MyClass.m 文件:
// Class Extension Definition in the implementation file
@interface MyClass()
@property (nonatomic, retain) NSString *myString;
@end
@implementation MyClass
- (id)init
{
self = [super init];
if( self )
{
// This property can only be accessed within the class
self.myString = @"Hello!";
}
}
@end
回答by kubi
Declare the property in the implementation (.m) file, like so:
在实现 (.m) 文件中声明属性,如下所示:
@interface MyClass()
@property (nonatomic, retain) MyPrivateClass *secretProperty;
@end
You'll be able to use that property within your class without a compiler warning.
您将能够在没有编译器警告的情况下在您的类中使用该属性。