Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly, non-mutable, public and readwrite, mutable, private @property: more information?

I want to expose an NSArray to my user (and I want them to only read it), but in my class, I want to use an NSMutableArray.

I tried the following code and it does not raise any warning:

// In the .h
@interface MyClass : NSObject <NSApplicationDelegate>

@property (nonatomic, readonly) NSArray * test ;

@end

and

// In the .m
@interface MyClass ()

@property (nonatomic, strong, readwrite) NSMutableArray * test ;

@end


@implementation MyClass

- (id)init
{
    self = [super init];
    if (self)
    {
        self.test = [[NSMutableArray alloc] init] ;
    }
    return self;
}

@end

But, if I try to access the @property test from within my class, I can use the method addObject:. So, I guess what precedes is not possible.

Why is there no warning as it is?

like image 911
Colas Avatar asked Oct 20 '22 14:10

Colas


1 Answers

I don't think that mixing property type would be a good practice. Instead I would create an accessor that returns a copy of the private mutable array. This is more conventional. Please note, don't use self for property access in your -init: method:

// In the .h
@interface MyClass : NSObject <NSApplicationDelegate>

- (NSArray *)test;

@end

// In the .m
@interface MyClass ()

@property (nonatomic, strong) NSMutableArray *aTest;

@end


@implementation MyClass

- (id)init
{
    self = [super init];
    if (self)
    {
        _aTest = [[NSMutableArray alloc] init] ;
    }
    return self;
}

- (NSArray *)test
{
    return [self.aTest copy];
}

@end
like image 184
vbali Avatar answered Oct 29 '22 14:10

vbali