CGRect type is a structure type. If I want to define a property as this type, should I use assign or retain attribute for this type?
@interface MyClass {
CGRect rect;
...
}
@property (nonatomic, assign) CGRect rect; // or retain?
or I have to write my own getter and setter?
Only assign
is possible for non-objects. (Before ARC, that includes CoreFoundation stuff, e.g. a CFArrayRef can only be assign
.)
@property (nonatomic, assign) CGRect rect;
// ^^^^^^ don't forget.
You don't need a custom getter and setter unless you don't want to use memcpy
for assignment.
@property (assign) CGRect rect;
CGrect
is a struct, not an NSObject
, so you cannot send message to it (like retain
).
You're full setup then will be something like:
// MyClass.h
@interface MyClass : NSObject
{
CGRect _rect;
}
@property (assign) CGRect rect;
and
// MyClass.m
@implementation MyClass
@synthesize rect=_rect;
@end
So basically you can then do something like:
MyClass *myClass = [[MyClass alloc] init];
myClass.rect = CGRectMake(0,0,0,0);
The synthesize directive basically makes two methods (getter/setter) for you "behind the scenes"; something like...
- (CGRect)rect;
- (void)setRect:(CGRect)value;
I usually add a "_" to my instance vars. The rect=_rect
is telling the compiler to modify the _rect instance var whenever the rect property is "called."
Have a read through these tutorials on Theocaco. He explains what the @synthesize(r) is doing behind the scenes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With