Difference between @property (nonatomic, readonly) and @property extension inside a class?

I have an Objective-c class "MyClass". In MyClass.m I have a class extension that declares a CGFloat property:

 @interface MyClass () @property (nonatomic) CGFloat myFloat; @end @implementation MyClass @synthesize myFloat; //... @end 

What changes (if any) when a property is declared using the readonly keyword?

 @interface MyClass () @property (nonatomic, readonly) CGFloat myFloat; @end @implementation MyClass @synthesize myFloat; //... @end 

Perhaps in the first case, I can say self.myFloat = 123.0; and CGFloat f = self.myFloat; inside MyClass? Then, in the second case, the readonly keyword prevents self.myFloat = 123.0; but allows you to read CGFloat f = self.myFloat;

+4
source share
3 answers

The readonly option means that only the getter method is declared for this property. Thus, without a setter, it cannot be changed using myObject.myFloat=0.5f;

If you do not declare it readonly , then it is read write by default.

Declaring your property through the () extension does not change the access mode, but changes the scope; this will be the "private" property.

+11
source

@synthesize uses the @property definition to create the appropriate getter / setter for iVar. When you specify readonly , a setter is not created. This is not strictly enforced, as you can write your own setter if you choose (although that doesn't make tons of sense).

Declaring a property in a category simply defines the scope of the property within that category.

+3
source

You are right in declaring your property as readonly , which you tell the compiler to not generate the setter method automatically, and therefore self.myFloat = 123.0; will be illegal (unless you create this method manually).

+1
source

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


All Articles