Is it possible to set readonly property value using KVC on iOS?

I am trying to describe my confusion here. Let me know if this question needs any changes.

Consistent with Apple documentation: The link for the readonly property is

Apple Documentation Link

Thus, we cannot set the readonly property because its setter will not be created. But I created a demo project to test this. I am sharing my sample code with you.

This is the ModelTest1.h class. It has the readonly property.

#import <Foundation/Foundation.h> @interface ModelTest1 : NSObject @property (readonly) NSMutableArray *arrTest; @end 

Now I set the value in it using KVC. Since this property is readonly, so at runtime it should give me an error, but this does not happen.

 - (void)readonlyTest { ModelTest1 *obj1 = [ModelTest1 new]; NSLog(@"obj1.arrTest before = %@",obj1.arrTest); [obj1 setValue:[NSMutableArray new] forKey:@"arrTest"]; NSLog(@"obj1.arrTest after = %@",obj1.arrTest); [obj1.arrTest addObject:@"Str 1"]; NSLog(@"obj1.arrTest after 2 = %@",obj1.arrTest); [obj1 release]; } 

Output:

Console exit

I do not understand why memory is allocated in NSMutableArray, even if it is read-only. And why does the string add readonly to this array.

I did this memory allocation test using NSString, also using KVC and getting the same result. The value was set read-only using KVC.

This is my confusion regarding setValue for the readonly property.

Am I misunderstanding something about readonly properties? or is something else going on?

+5
source share
1 answer

The documentation you cite specifically refers to the setter method. This is not the same as KVC. KVC, by default, sets the base instance variable directly if it cannot find the setter method to invoke. Thus, readonly suppresses the synthesis of the setter method, but it does not stop KVC.

You can disable this feature (the ability of KVC to jump directly to an instance variable) by setting the accessInstanceVariablesDirectly class to NO, but the default is YES.

+10
source

Source: https://habr.com/ru/post/1235818/


All Articles