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?
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
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