Private Property in Objective C

Is there a way to declare private property in Objective-C? The goal is to capitalize on synthesized getters and setters that implement a specific memory management scheme but are not published.

Attempting to declare a property within a category results in an error:

@interface MyClass : NSObject { NSArray *_someArray; } ... @end @interface MyClass (private) @property (nonatomic, retain) NSArray *someArray; @end @implementation MyClass (private) @synthesize someArray = _someArray; // ^^^ error here: @synthesize not allowed in a category implementation @end @implementation MyClass ... @end 
+59
objective-c
Apr 13 2018-11-11T00:
source share
4 answers

I implement my private properties as follows.

Myclass.m

 @interface MyClass () @property (nonatomic, retain) NSArray *someArray; @end @implementation MyClass @synthesize someArray; ... 

That is all you need.

+85
Apr 13 2018-11-11T00:
source share

A. If you want a completely private variable. Do not give him property.
B. If you want the readonly variable, accessible externally from the encapsulation of the class, to use a combination of the global variable and the property:

 //Header @interface Class{ NSObject *_aProperty } @property (nonatomic, readonly) NSObject *aProperty; // In the implementation @synthesize aProperty = _aProperty; //Naming convention prefix _ supported 2012 by Apple. 

Using the readonly modifier, we can now access the property elsewhere.

 Class *c = [[Class alloc]init]; NSObject *obj = c.aProperty; //Readonly 

But internally, we cannot set aProperty inside the class:

 // In the implementation self.aProperty = [[NSObject alloc]init]; //Gives Compiler warning. Cannot write to property because of readonly modifier. //Solution: _aProperty = [[NSObject alloc]init]; //Bypass property and access the global variable directly 
+9
Feb 27 '13 at 0:34
source share

As others have pointed out, (currently) there is no way to truly declare private property in Objetive-C.

One of the things you can do to try to “protect” properties in some way is to have a base class with a property declared readonly , and in your subclasses you can override the same property as readwrite .

Apple's documentation on updated properties can be found here: http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW19

+6
Apr 13 2018-11-11T00:
source share

It depends on what you mean by "private".

If you just mean “not publicly documented”, you can easily use the class extension in a private header or in a .m file.

If you mean "others can't call it at all," you're out of luck. Anyone can call a method if they know their name, even if it is not publicly documented.

+5
Apr 13 2018-11-11T00:
source share



All Articles