Archive for 3月 30th, 2010

iPhone プログラミングノート #1

さてさて、iPhone SDK アプリケーション開発ガイドをパラパラ見ること3章、おぼろげながらiPhoneのプログラミング方法がわかって来たのでちょいと備忘録でも。

で、とりあえずテキトーにiPhoneのプロジェクトを作る。
とりあえずWindow-based Applicationとかで。
恐らく下記のようなファイルが出来るはず。
Classes
・プロジェクト名AppDelegate.h
・プロジェクト名AppDelegate.m
Other Resources
・main.m
・プロジェクト名-Info.plist

あと、その他諸々ついてくるけど、とりあえず気にしないことに。
ただこのままだと○○.xibというファイルを読み込んでしまうので、それを防がなくてはならない。
とりあえずInfo.plistを開いて「Main nib file base name」の項目自体を削除、と。

XML形式で開いてしまったら、当該箇所をやはり削除。
例えば下記のような2行があったら削除。

	<key>NSMainNibFile</key>
	<string>MainView.nib</string>

ちなみに、プロジェクト名はHelloWorld・・・と言うことで。

で、エントリーポイント(プログラム実行時、最初に呼び出される関数)はC/C++と同様main。
で、Windowsのように自動でプログラムのループを司るWinMainのような仕組みは、mainに書くことになっているみたい。
ひな形として与えられるのは下記の通り。

#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {

	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	int retVal = UIApplicationMain(argc, argv, nil, nil);
	[pool release];
	return retVal;
}

なんか、argcとargvをUIApplicationMainに突っ込んでる所からして、ここがプログラムループ、らしい。。
ここの第4引数を下記のように修正。

	int retVal = UIApplicationMain(argc, argv, nil, @"HelloWorldAppDelegate");

ちなみに、.mとか.hとか付けていないのはわざとなので付けないこと。

お次はHelloWorldAppDelegate.hと同.mを編集。

// HelloWorldAppDelegate.h
#import <UIKit/UIKit.h>

// メッセージ表示用にUITextViewと言うビューを継承し、カスタムビューを作成
@interface CustomView : UITextView
{
	// カスタムビュー用のメンバ変数
	UITextView *myTextView;
}

@end

@interface HelloWorldAppDelegate : NSObject <UIApplicationDelegate> {
	UIWindow *window;
	CustomView *mainView;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@end
// HelloWorldAppDelegate.m
#import "HelloWorldAppDelegate.h"

@implementation CustomView

- (id)initWithFrame:(CGRect)frame {
	// 親クラスの親メソッド呼び出し
	self = [super initWithFrame:frame];

	// 親メソッド取得成功時のみ実行
	if (self != nil) {
		// テキストビューを初期化
		myTextView = [[UITextView alloc] initWithFrame:frame];
		// テキストビューへテキスト追加
		myTextView.text = @"おはこんばんちは";
		// テキストビューをこのカスタムビューに適用?
		[self addSubview:myTextView];
	}
	return self;
}

- (void)dealloc {
	// メモリ解放
	[myTextView release];
	[super dealloc];
}
@end

@implementation HelloWorldAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {
	// バウンズ(画面領域)を取得
	CGRect bounds = [[UIScreen mainScreen] applicationFrame];

	// ウィンドウの範囲を画面サイズギリギリまで占有
	window = [[UIWindow alloc] initWithFrame:bounds];
	// ビューのサイズをステータスバーを除いて占有
	mainView = [[CustomView alloc] initWithFrame:CGRectMake(0, 0, bounds.size.width, bounds.size.height)];

	// ウィンドウへビューを設定
	[window addSubview:mainView];
	// ビューを表示
	[window makeKeyAndVisible];
}

- (void)dealloc {
	[mainView release];
	[window release];
	[super dealloc];
}
@end

これをコンパイルするとこんな感じ。

ふむふむ、何となくわかったような、わからないような。
実際はこの次のViewControllerまでやってるんだけど、復習はここまで。
本のコードとちょっと違うのはやはりわざと。
行儀が良いのか悪いのかは知らんけど、これでも動く。

そんだけ。

Post to Twitter

, , , , ,

No Comments

Bad Behavior has blocked 19 access attempts in the last 7 days.