Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 anything) when the 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 the assignment self.myFloat = 123.0; but allows the read CGFloat f = self.myFloat;

like image 810
SundayMonday Avatar asked Dec 06 '22 18:12

SundayMonday


2 Answers

The option readonly means that only the getter method is being declared for this property. Thus, without a setter, it can't be modified via myObject.myFloat=0.5f;

If you don't declare it readonly, it's read write by default.

Declaring your property via () extension does not modify the access mode but it modifies the scope; it will be a "private" property.

like image 123
javieralog Avatar answered Jan 19 '23 00:01

javieralog


@synthesize uses the @property definition to generate the appropiate getter/setter for the iVar. When you specify readonly, no setter is generated. This is not strictly enforced as you can write your own setter if you choose (though that doesn't make a ton of sense).

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

like image 29
XJones Avatar answered Jan 19 '23 01:01

XJones