前回UbuntuにObjective-Cのコンパイラをインストール、さらには簡単なプログラムをコンパイルして実行までやりました。
が、作ったプログラムが全然Objective-Cっぽくないので、今回はObjective-Cっぽい簡単なプログラムを試してみたいと思います。
まずhello.hファイルを作って以下のように記載します。
C:
-
#import <objc/Object.h>
-
-
@interface Personal : Object
-
{
-
int height, weight, age;
-
}
-
- (void)setInfo: (int)height: (int)weight: (int)age;
-
- (void)printInfo;
-
@end
続いてhello.mファイルを以下のように記載します。
C:
-
#import <objc/Object.h>
-
#import "hello.h"
-
-
@implementation Personal
-
- (void)setInfo: (int)height: (int)weight: (int)age {
-
self->height = height;
-
self->weight = weight;
-
self->age = age;
-
}
-
-
- (void)printInfo {
-
}
-
@end
-
-
int main() {
-
-
id personal = [Personal alloc];
-
[personal setInfo: 175: 75: 33];
-
-
[personal printInfo];
-
-
return 0;
-
}
続いてコンパイルをします。
ubuntu@ubuntu-desktop:~/c$ gcc hello.m -lobjc
hello.m: In function ‘-[Personal setInfo:::]’:
hello.m:6: 警告: local declaration of ‘height’ hides instance variable
hello.m:7: 警告: local declaration of ‘weight’ hides instance variable
hello.m:8: 警告: local declaration of ‘age’ hides instance variable
クラス変数とメソッドの引数の名前が重複しているので警告が表示されますが、プログラム上はselfをつけて明示的に使いわけているのでこの警告は無視しても大丈夫です
ubuntu@ubuntu-desktop:~/c$ ./a.out
あなたは身長175cm、体重75kg、年齢33歳です
hello.m: In function ‘-[Personal setInfo:::]’:
hello.m:6: 警告: local declaration of ‘height’ hides instance variable
hello.m:7: 警告: local declaration of ‘weight’ hides instance variable
hello.m:8: 警告: local declaration of ‘age’ hides instance variable
クラス変数とメソッドの引数の名前が重複しているので警告が表示されますが、プログラム上はselfをつけて明示的に使いわけているのでこの警告は無視しても大丈夫です
ubuntu@ubuntu-desktop:~/c$ ./a.out
あなたは身長175cm、体重75kg、年齢33歳です
という感じでObjectiveな感じのプログラムが完成しました。
Objective-Cのソースコードを最初見たときはとっつきにくそうな言語だなぁと思ったのですが、実際にコードを記述してみると意外といけそうな気がしてきました(←単純)
