Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a private property?

I tried to make a private property in my *.m file:

@interface MyClass (Private)
@property (nonatomic, retain) NSMutableArray *stuff;
@end

@implementation MyClass
@synthesize stuff; // not ok

Compiler claims that there's no stuff property declared. But there's a stuff. Just in an anonymous category. Let me guess: Impossible. Other solutions?

like image 920
dontWatchMyProfile Avatar asked May 04 '10 20:05

dontWatchMyProfile


People also ask

How do I make properties private in JavaScript?

Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.

What is private property Singapore?

What is considered private property in Singapore? In Singapore, properties fall under two categories: public (HDB flats), and private housing. In this article, we refer to private properties as condominiums, landed property, and executive condominiums (ECs).

What are private properties in JavaScript?

The private keyword in object-oriented languages is an access modifier that can be used to make properties and methods only accessible inside the declared class. This makes it easy to hide underlying logic that should be hidden from curious eyes and should not be interacted with outside from the class.


1 Answers

You want to use a "class extension" rather than a category:

@interface MyClass ()
@property (nonatomic, retain) NSMutableArray *stuff;
@end

@implementation MyClass
@synthesize stuff; // ok

Class extensions were created in Objective-C 2.0 in part specifically for this purpose. The advantage of class extensions is that the compiler treats them as part of the original class definition and can thus warn about incomplete implementations.

Besides purely private properties, you can also create read-only public properties that are read-write internally. A property may be re-declared in a class extensions solely to change the access (readonly vs. readwrite) but must be identical in declaration otherwise. Thus you can do:

//MyClass.h
@interface MyClass : NSObject
{ }
@property (nonatomic,retain,redonly) NSArray *myProperty;
@end

//MyClass.m
@interface MyClass ()
@property (nonatomic, retain, readwrite) NSArray *myProperty;
@end

@implementation MyClass
@synthesize myProperty;
//...
@end
like image 153
Barry Wark Avatar answered Sep 17 '22 16:09

Barry Wark