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

前端 未结 3 1179
一向
一向 2020-12-11 00:29

I’d like to declare a public immutable property:

@interface Foo
@property(strong, readonly) NSSet *items;
@end

…backed with a mutable type

相关标签:
3条回答
  • 2020-12-11 01:09

    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 讨论(0)
  • 2020-12-11 01:18

    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.

    0 讨论(0)
  • 2020-12-11 01:21

    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
    
    0 讨论(0)
提交回复
热议问题