Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGRect var as property value?

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?

like image 547
David.Chu.ca Avatar asked Jun 04 '10 06:06

David.Chu.ca


2 Answers

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.

like image 110
kennytm Avatar answered Oct 22 '22 23:10

kennytm


@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.

like image 24
typeoneerror Avatar answered Oct 22 '22 23:10

typeoneerror