Objective-C 事始め

iPhone開発環境も手に入ったことだし、さらっと Objective-C の勉強でもしてみることにしてみました

右も左もわからない世界なんでとりあえずは、Counter を作ってみることにしました。

/// おなじみのカウンター
@interface Counter : NSObject
{
	int m_count;
	int m_step;
}

/// 初期化
- (id) initWithValue:(int)i_val step:(int)i_step;

/// インクリメント
- (id) inc;

/// デクリメント
- (id) dec;

/// 現在の値取得
- (int) get;
@end

@implementation Counter

/// 初期化
- (id) initWithValue:(int)i_val step:(int)i_step
{
	self = [super init];
	m_count = i_val;
	m_step = i_step;

	return self;
}

/// インクリメント
- (id) inc
{
	m_count += m_step;
	return self;
}

/// デクリメント
- (id) dec
{
	m_count -= m_step;
	return self;
}

/// 現在の値取得
- (int) get
{
	return m_count;
}
@end


int main(int argc, char *argv[])
{
	id a_counter00 = [[Counter alloc] initWithValue:0 step:1];
	id a_counter01 = [[Counter alloc] initWithValue:100 step:2];

	printf( "count %d, %d\n", [a_counter00 get], [a_counter01 get] );

	for( int i = 0; i < 2; i++ ){
		printf( "inc %d, %d\n", [[a_counter00 inc] get], [[a_counter01 inc] get] );
	}

	for( int i = 0; i < 2; i++ ){
		printf( "dec %d, %d\n", [[a_counter00 dec] get], [[a_counter01 dec] get] );
	}

	return 0;
}

何となくコードに気持ち悪さを感じるのは、慣れの問題なんでしょう

郷に入れば、郷に従え...と行きたいところですが、新しい文法に慣れるのは少し時間がかかりそうです

メンバ関数(って呼んでいいのかな?)の引数指定に、イニシャライザ(合ってる?)を利用するのが不思議な感じ

軽くドキュメントを読んでいた時点では、「C/C++みたいに無意味な数字が並ぶよかわかりやすいから良いかも」って思っていたんだすけど、いざ使ってみると名前のつけ方に困るなぁと...

C++なんかだと

class Counter
{
  public:
    Counter( int i_val, int i_step )
    {
    }
};

って書けるのが、

- (id)initWithVal:(int)i_val step:(int)i_step;

ですからねぇ...
イニシャライザがついているんだから、変数名はaとかbとか簡素なものを使った方がコードが読みやすいのかしら


...ま、少し慣れるまでは、Objective-C で遊んでみることにします