开发者

How to make properties private?

Someone told me I could make properties private so that only an instance of the class can refer to th开发者_开发知识库em (via 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.


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.

So if this is your MyClass.m file:

// 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


Declare the property in the implementation (.m) file, like so:

@interface MyClass()

@property (nonatomic, retain) MyPrivateClass *secretProperty;

@end

You'll be able to use that property within your class without a compiler warning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜