How would you return an object from a method, so it is read-only for the caller?
Please note that this isn’t a property that can be simply set to read-only when it’s getter is declared
i.e @property(nonatomic,retain,readonly) NSDate* pub_date;
For example:
-(SomeClass*)getObject
{
SomeClass* object = [[SomeClass alloc] init];
//Don't allow writing to 'object'
return object;
}
Thanks.
It depends what the object is. If it has a mutable / immutable pair (like
NSString/NSMutableString) then your getter method can return the immutable version.Otherwise, you can’t control the behaviour of other objects – once you’ve returned an object, there is no control over it from the object that originally provided it.
If you are concerned that another object may alter an object returned from a getter, and thereby amend the property held within the original object, then you should return a copy of the object instead.
Example:
Object A has a mutable string property, object B asks for this mutable string, the getter directly returns the instance variable backing the property.
Object B then changes the string – the property of object A has also been amended because both objects have a pointer to the same mutable string.
In this case, you would return a copy of the object rather than the object itself. If your object is a custom one, you must implement the
NSCopyingprotocol to allow this.A further note – declaring a property as read only simply means that no setter accessor will be generated – i.e.
objectA.property = newValue;will result in a compiler error.