2011年2月8日 星期二

[Objective-C] Classes 筆記 (3) - Property 屬性 (setter & getter)

在Objective-C 2.0之後, 可以透過@property@synthesize來達到setter & getter的效果(或稱accessors & mutators)

  • MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject {
 NSString *name;
 NSInteger age;
}

@property (nonatomic, retain) NSString *name; 
@property NSInteger age;

@end

  • MyClass.m
#import "MyClass.h"
@implementation MyClass
@synthesize name, age;
@end

  • 實際使用
MyClass *myClass = [MyClass alloc];
//--setter
myClass.name = @"Hank";

//--getter
NSLog(@"%@", myClass.name);
NSLog(@"%@", [myClass name]);


Reference

Beginning-iOS-4-Application-Development
The Objective-C Programming Language: Defining a Class
Related Posts Plugin for WordPress, Blogger...