Objective-C for AS3.0 Developers: How to automate getters & setters

In AS3.0 we sometimes have to type a bunch of repetitive lines of code to create Getter & Setter functions that look like this:

protected var _property1:String;
protected var _property2:String; 
//...
public function set property1(p1:String):void { _property1 = p1; }
public function get property1():String { return _property1; }
public function set property2(p2:String):void { _property2 = p2; }
public function get property2():String { return _property2; }
//...	

There’s a shortcut in Objective-C.

If you want, you can manually write out getter & setter methods. It might be useful for those who prefer clarity more than using code shortcuts. However, in this example, the lines that start with @property in the header file and @synthesize in the implementation file allow you to skip the often tedious task of typing up Getters & Setters:

//MyClass.h file
@interface MyClass: NSObject
{
    int *property1;
    int *property2;
}

@property(nonatomic, readwrite) int *property1;
@property(nonatomic, readwrite) int *property2;

//...
@end

//MyClass.m file
@implementation MyClass

@synthesize property1;
@synthesize property2;

//...
-(void)dealloc
{
    [text release];
    [super dealloc];
}
@end

An example from UIKit framework

@property calls are listed in the iPhone equivalent of the asdoc (AS3.0 api documentation). In this case, for a class called UIImageView, and it’s property animationRepeatCount, the documentation lists:

@property(nonatomic) NSInteger animationRepeatCount 

Which means you can use setAnimationRepeatCount as the Setter method for animationRepeatCount whenever you have a variable of type UIImageView. Here’s a video tutorial that uses the setter for this property.

You can also see @property calls in the UIImageView.h header file in the SDK folder on your machine. The path is something like:
YOUR_HARD_DRIVE/Developer/Platforms/iPhoneOS.platform/
Developer/SDKs/iPhoneOS3.1.3.sdk/System/Library/Frameworks/
UIKit.framework/Headers/UIImageView.h

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s