Saturday, December 20, 2008

property and synthesize directives in Objective C 2.0

@property directive is to declare a property

@interface Test : NSObject {
}
@property (readwrite,assign) int var1
@property (readonly,assign) int var2
@property (getter=foo, setter=foo1:) int var3
@end

readwrite attribute (default) tells the compiler to generate both getter and setter accessors

readonly attribute tells the compiler not to generate a setter accessor

assign attribute to implement set-by-assignment (i.e. generate setter and simply assigns a value to the instance variable)

-(void) setVar1:(NSString *)s
{
var1 = s;
}


copy attribute to implement set-by-copy (usually for mutable object)

-(void) setVar1:(NSString *)s
{
[var1 release];
var1 = [s copy];
}


retain attribute to implement set-by-retainment (i.e. generate setter and retain a value before assignment)

-(void) setVar1:(NSString *)s
{
[s retain];
[var1 release];
var1 = s;
}



@synthesize directive is to make the compiler generate accessors

@implementation Test
@synthesize var1;
@synthesize var2;
@dynamic var3;
@end

By Default, these messages are named var1 and setVar1 where var1 is the name of the variable



dynamic attribute tells the compiler not to generate any accessor messages









Here is a good guideline for memory management in Cocoa
http://oreilly.com/pub/a/mac/excerpt/Cocoa_ch04/index.html

Retention Count rules
  • Within a given block, the use of -copy, -alloc and -retain should equal the use of -release and -autorelease.
  • Objects created using convenience constructors (e.g. NSString's stringWithString) are considered autoreleased.
  • Implement a -dealloc method to release the instance variables you own

  • retain increases the reference count of an object by 1
  • release decreases the reference count of an object by 1
  • autorelease decreases the reference count of an object by 1 at some stage in the future
  • alloc allocates memory for an object, and returns it with retain count of 1
  • copy makes a copy of an object, and returns it with retain count of 1






No comments: