开发者

How to declare an immutable property backed by a mutable type?

开发者 https://www.devze.com 2023-04-12 02:38 出处:网络
I’d like to declare a public immutable property: @interface Foo @property(strong, readonly) NSSet *items;

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开发者_如何学JAVA 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
0

精彩评论

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

关注公众号