I’d like to declare a public immutable property:
@interface Foo
@property(strong, readonly) NSSet *items;
@end
…backed with a mutable type in the implementation file:
@interface Foo (/* private interface*/)
@property(strong) NSMutableSet *items;
@end
@implementation
@synthesize items;
@end
What I want is a mutable collection in the implementation that gets cast into an immutable one when accessed from the outside. (I don’t care that the caller can cast the instance back to NSMutableSet
and break the encapsulation. I live in a quiet, decent town where such things don’t happen.)
Right now my compiler treats the property as NSSet
inside the implementation. I know there are many ways to get it working, for example with custom getters, but is there a way to do it simply with declared properties?
The easiest solution is
@interface Foo {
@private
NSMutableSet* _items;
}
@property (readonly) NSSet* items;
and then just
@synthesize items = _items;
inside your implementation file. Then you can access the mutable set through _items but the public interface will be an immutable set.
You have to declare the property in the public interface as readonly in order the compiler not to complain. Like this:
Word.h
#import <Foundation/Foundation.h>
@interface Word : NSObject
@property (nonatomic, strong, readonly) NSArray *tags;
@end
Word.m
#import "Word.h"
@interface Word()
@property (nonatomic, strong) NSMutableArray *tags;
@end
@implementation Word
@end
You could just do it yourself in your implementation:
@interface Foo : NSObject
@property(nonatomic, retain) NSArray *anArray;
@end
--- implementation file ---
@interface Foo()
{
NSMutableArray *_anArray;
}
@end
@implementation Foo
- (NSArray *)anArray
{
return _anArray;
}
- (void)setAnArray:(NSArray *)inArray
{
if ( _anArray == inArray )
{
return;
}
[_anArray release];
_anArray = [inArray retain];
}
- (NSMutableArray *)mutablePrivateAnArray
{
return _anArray;
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With