Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make properties private?

Someone told me I could make properties private so that only an instance of the class can refer to them (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.

like image 474
Randall Avatar asked Aug 09 '11 14:08

Randall


People also ask

How do I make my object property private?

If you really want a property to be private in the usual sense--meaning it cannot be accessed from outside methods on the object--then some options include: Use TypeScript and its private keyword. This will cause attempted external accesses to throw a compile-time error.

How do I make properties private in JavaScript?

Use closure() to Create Private Properties in JavaScript Using closure() is one of the choices to implement private properties in JavaScript. Inner functions with access to the variables of the surrounding function are known as closures.

Can properties be private in C#?

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.

What is a private method?

Private methods are those methods that should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private methods that cannot be accessed except inside a class. However, to define a private method prefix the member name with the double underscore “__”.


1 Answers

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
like image 150
dtuckernet Avatar answered Oct 05 '22 14:10

dtuckernet