Last Update 2013/02/13
TOP - Objective-C - クラス - self
メソッド定義内において、「self」はメソッドを実行するインスタンスオブジェクト自体を参照する変数です。代入も可能です。
(例)
MyTestClass.h
MyTestClass.h
#import <Foundation/Foundation.h>
@interface MyTestClass : NSObject
{
NSString *messageString;
}
- (id)initWithMessage: (NSString *)msgString;
- (NSString *)messageString;
@end
MyTestClass.m
#import "MyTestClass.h"
@implementation MyTestClass
- (id)initWithMessage: (NSString *)msgString
{
if (self = [super init]) // ここで使用
{
messageString = [[NSString alloc] initWithString:msgString];
}
return self;
}
- (NSString *)messageString
{
return messageString;
}
@end
main.m
#import "MyTestClass.h"
int main (void)
{
MyTestClass *mtc = [[MyTestClass alloc] initWithMessage:@"test"];
NSLog(@"message : %@", [mtc messageString]);
return 0;
}
実行結果
message : test