実装方法
1. プロパティの宣言
*.hファイルに次の書式でプロパティを宣言する。
@property (属性)型名 プロパティ名;
属性は、アクセス制限を加えたり、オブジェクトの代入時の操作を記述します。nonatomicであれば同期処理を行わないなどです。
2. プロパティの実装
*.mファイルに次の書式でプロパティを実装する。
@synthesize プロパティ名=インスタンス変数;
また、必要に応じてinitやdeallocで初期化やメモリ解放を実装する。
これで、外部クラスからは"オブジェクト名.プロパティ名"でアクセスできるようになっています。具体例として、Informationクラスにプロパティを実装し、そのプロパティをiPhoneアプリ開発環境を整えるで作成したHelloクラスから利用するように変更しました。
Information.h
#import <Foundation/Foundation.h>
@interface Information : NSObject {
NSString* _description;
}
@property (nonatomic,retain)NSString* description;
@end
Information.m
#import "Information.h"
@implementation Information
@synthesize description = _description;
- (id)init {
self=[super init];
if (self) {
_description=@"";
}
return self;
}
- (void)dealloc {
[_description release];
}
@end
Hello.m
#import "Hello.h"
#import "Information.h"
@implementation Hello
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor=[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
UIFont* font=[UIFont systemFontOfSize:18];
Information* information = [[[Information alloc] init] autorelease];
information.description = @"Hello World";
[information.description drawAtPoint:CGPointMake(0, 0) withFont:font];
}
@end
実行すると、Hello Worldがちゃんと表示されました。
0 件のコメント:
コメントを投稿