LoginSignup
1
1

More than 5 years have passed since last update.

[OSX][iOS]Objective-C

Posted at

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 Advent Calendar 2015

Cocoa in a Nutshell: A Desktop Quick Reference

【Cocoa練習帳】
http://www.bitz.co.jp/weblog/

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

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1