Ubuntu 資料一覧

Objective-CのFoundationクラスを使用する

2010/5/5更新

対応バージョン: 10.04

UbuntuでObjective-CのFoundationクラスを使用するには以下の手順で行う。

libgnustep-base-devパッケージインストール
% sudo aptitude install libgnustep-base-dev
gccのオプション指定
% gcc <ソース> -lobjc -lgnustep-base -I/usr/include/GNUstep \
-fconstant-string-class=NSConstantString
-fconstant-string-class=NSConstantStringオプション

ソース中の@"..."ディレクティブをNSConstantStringクラスのインスタンスとして処理するためのオプション。

これを付けないとNXConstantStringクラスのインスタンスとして処理されるので以下のエラーになる。

error: cannot find interface declaration for NXConstantString
ソースにメモリ自動解放機構組み込み

main()関数の先頭でオブジェクトの自動解放プールを生成し、メモリ管理を行いたいオブジェクトからautoreleaseメッセージを送信してプールに登録、最後にプールからdrainメッセージを送ってプールを破棄する。

void main() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
:
    id <オブジェクト> = [[<クラス> alloc] autorelease];
:
    [pool drain];
}

コード例)

% vi test.m

#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#import <stdio.h>

// クラス宣言
@interface Text : NSObject {
    NSString *message;
}
- (void)setMessage :(NSString *)text;
- (void)printMessage;
@end

// クラス定義
@implementation Text : NSObject
- (void)setMessage :(NSString *)text {
    message = text;
}
- (void)printMessage {
    printf("%s\n", [message UTF8String]);
}
@end

// メイン
void main() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    id text = [[Text alloc] autorelease];
    [text setMessage:@"Hello World"];
    [text printMessage];

    [pool drain];
}

% gcc test.m -lobjc -lgnustep-base -I/usr/include/GNUstep \
-fconstant-string-class=NSConstantString
% ./a.out
Hello World

関連資料・記事