トップ «前の日記(2015-12-01) 最新 次の日記(2015-12-04)» 編集

Cocoa練習帳

iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど

2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|

2015-12-02 [OSX][iOS]Objective-C

Objective-C 2.0と呼ばれるものから、大幅に機能が増えたが、当初のObjective-Cは簡素で、C言語をマスターしたプログラマーなら30分程度でマスターできる言語だった。ただし、言語の仕様を簡素というだけで、Cocoaフレームワークを使いこなせるようになるには、当初から難しかったが。

今回の投稿では、初期のCocoaでのObjective-Cについて説明する。これによって、基本的にとても簡素な仕様の言語だとうことが分かると思うので。

クラス定義は、以下の通り。通常、ヘッダーファイルに記述される。

#import <Cococa/Cocoa.h>
 
@interface Song : NSObject {
    NSString *title;
}
 
+ (id)sharedInstance;
- (id)init;
- (void)dealloc;
- (NSString *)title;
- (void)setTitle:(NSString *)aTitle;
@end

クラスは必ずNSObjectまたは、その子クラスを継承する必要がある。

クラスの実装は、以下の通り。通常、サフィックスが.mのファイルに記述される。

#import "Song.h"
 
@implementation Song
 
+ (id)sharedInstance
{
    static Song* song = nil;
    if (! song) {
        song = [[Song alloc] init];
    }
    return song;
}
 
- (id)init
{
    if (self = [super init]) {
        title = nil;
    }
    return self;
}
 
- (void)dealloc
{
    if (title) {
        [title release];
        title = nil;
    }
    [super dealloc];
}
 
- (NSString *)title
{
    return title;
}
 
- (void)setTitle:(NSString *)aTitle
{
    [title autorelease];
    title = [aTitle retain];
}
 
@end

+で始まるのはクラスメソッド。-で始まるのはインスタンスメソッド。親クラスのインスタンスはselfとなる。

既存のクラスはカテゴリーを使って拡張できる。

#import "Song.h"
 
@interface Song (Album)
 
- (NSString *)albumTitle;
 
@end
#import "Album.h"
 
@implementation Song (Album)
 
- (NSString *)albumTitle
{
    return @"Trout Mask Replica";
}
 
@end

多重継承に対応しない代わりに、プロトコルという機能を用意している。

@protocol Playable
- (void)play;
- (void)stop;
@end

Songクラスがこれに対応してみる。

#import <Cococa/Cocoa.h>
#import "Playable.h"
 
@interface Song : NSObject <Playable> {
    NSString *title;
}
 
- (void)play;
- (void)stop;

呼び出し側はプロトコルに対応しているか判定することができる。

if ([song conformsTo:@protocol(Playable)]) {
    [song play];
}
else {
}

_ 【Cocoa練習帳】

http://www.bitz.co.jp/weblog/
http://ameblo.jp/bitz/(ミラー・サイト)

トップ «前の日記(2015-12-01) 最新 次の日記(2015-12-04)» 編集