I read others few topics about it, but still I'm lost.
I want to create 2 kind of objects, one immutable with only "readonly" properties, and one mutable with only "readwrite" properties.
Lets call them EXCar and EXMutableCar.
EXCar is subclass of NSObject, and EXMutableCar is Subclass of EXCar.
ExCar will have in its interface
@property (nonatomic, strong, readonly) NSString *name;
EXMutableCar will have in its interface
@property (nonatomic, strong) NSString *name;
So I "open" properties of EXCar when I use its subclasse EXMutableCar. And then it's mutable. The problem is to copy properly between them.
I implemented mutableCopyWithZone in EXCar :
- (id)mutableCopyWithZone:(NSZone *)zone {
EXMutableCar *mutableCopy = [[EXMutableCar allocWithZone:zone] init];
mutableCopy.name = _name;
return mutableCopy;
}
First question, is it the good way to do it ? (I want swallow copy)
The problem is with copyWithZone. Since the properties of EXCar are readonly I cannot create neither in EXCar, neither in EXMutableCar a new instance of EXCar and fill its properties like this :
- (id)copyWithZone:(NSZone *)zone {
EXCar *copy = [[EXCar allocWithZone:zone] init];
copy.name = _name; // This can't work...
return copy;
}
And I don't really want to do an "init" method with 15 properties to pass in (for sure, EXCar is an example, real classes are full of many properties). And normally they are initiated from JSON message from server, so they don't need a complicate init method.
Second question is so, how to do a copyWithZone that keep my class immutable ?
Thanks for your help :)
Code:
Explanation:
EXCar
interface implements both "copying" protocols;EXMutableCar
overrides the same property, making itreadwrite
.First thing in
EXMutableCar
implementation: manually@synthesize name
because Xcode gives us a warning, since we have the same property (but with different access specifier) in our superclass.Note we could have given the same name to our instance variable, like
_name
, but it is important to understand that we declare in subclass a different variable, since_name
from the superclass is inaccessible for us.Next, Apple documentation states:
same for NSMutableCopying:
We do declare additional instance variables, so we override these methods in our subclass as well.
Result: