views:

212

answers:

2

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?

+2  A: 

Only assign is possible for non-objects. (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.

KennyTM
Thanks. Do I need to have my own setting to assign field by field in code?
David.Chu.ca
@David: If it's CGRect, assigning field by field is equivalent to `memcpy`.
KennyTM
+1  A: 
@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.

Typeoneerror
That makes sense. Still not sure what is the generated codes to do the assignment, memory or field-by-field? I edited my question.
David.Chu.ca