Question

I have 2 classes as per below:

Class ModelA.h

@interface ModelA : NSObject
   @property (nonatomic, strong) NSArray *arrayA;
@end

Class ControllerA.m

@interface ControllerA()
    @ property (nonatomic, copy, readonly) ModelA *modelProperty;
@end

@implementation ControllerA

- (void)someMethod:(NSArray *)sampleArray
{
    self.modelProperty.arrayA = sampleArray;
}

If I try to assign something to self.modelProperty, I get a build error which says I cannot since its a readonly property. But I assign something to its property it XCode doesn't give any error i.e. self.modelProperty.arrayA = sampleArray just builds fine. However when I debug through it and print self.modelProperty.arrayA I get nil even though sampleArray has data in it.

Question: Is it possible to assign values to a property of a readonly object?

Was it helpful?

Solution

Is it possible to assign values to a property of a readonly object?

Er, sort of. The language you used is slightly confusing. It isn't a readonly object; it's a readonly property. And it is possible to assign values to the object stored in a readonly property.

readonly just means that you can't set that property -- there is no setModelProperty: setter method.

It does not mean that the target of the object is immutable. It's not analogous to const. All it means is that you can't set the property.

The reason you're seeing nil is that any message sent to nil returns nil.

self.modelProperty.arrayA

Is the same as:

[[self modelProperty] arrayA]

If modelProperty is nil (which it is, from the code you've shown), this is the same as:

[nil arrayA]

Which returns nil -- in the same way that [nil anyMethod] returns nil.


Final note: you have copy set as the memory policy for the modelProperty property, but the ModalA class doesn't appear implement the NSCopying protocol. Are you sure you don't want strong?

OTHER TIPS

Try: _modelProperty = sampleArray

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top