5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【ぶっちゃけiOSアプリ開発】手っ取り早くObjective-cを理解する | その2 クラスの初期化

Last updated at Posted at 2017-11-29

細かいことや例外的なことは後回しでいいので、手っ取り早くobjective-cを理解して使い始めたいという人向けです。他言語を経験していることが前提です。
その2はクラスの初期化方法です。

#サンプルクラスQiitaTest
コンソールにメッセージ出力するだけのメソッドを実装したクラス。

QiitaTest.h
#import <Foundation/Foundation.h>

@interface QiitaTest : NSObject

- (void)consoleWrite;

@end
QiitaTest.m
#import "QiitaTest.h"

@implementation QiitaTest

- (void)consoleWrite {
    NSLog(@"Good Morning!"); // コンソールにメッセージ出力する
}

@end

※NSLog
c言語のprintfみたいなもの。「NS~」という独特のクラスについては別の記事で書く

#クラスを初期化してメソッドを呼び出す
ViewControllerを使った場合。

ViewController.m
#import "ViewController.h"
#import "QiitaTest.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    QiitaTest *test = [[QiitaTest alloc] init]; // クラスを初期化する
    [test consoleWrite]; // メソッドを呼び出す
}

@end

実行すると、Xcodeのログに以下のメッセージが出力される。

2017-11-29 23:02:10.599 QiitaTest[1186:37521] Good Morning!

クラスの初期化は以下の行で行っている。

QiitaTest *test = [[QiitaTest alloc] init];

とりあえずクラスを初期化するためには、おまじないのように書いておけば良い。
#クラスの初期化をもっと知りたい人

QiitaTest *test = [[QiitaTest alloc] init];

この行は以下のように書き換えられる。

QiitaTest *test = [QiitaTest alloc];
test = [test init];

1行目でQiitaTestクラスのallocというクラスメソッドを呼び出し、インスタンス化してtestオブジェクトをメモリ上に確保。
2行目でtestオブジェクトのinitというインスタンスメソッドを呼び出して初期化。
この2行を1行にまとめたもの。


ぶっちゃけiOSアプリ開発は、アプリ開発にあたってとりあえず知っておくべきことをズバリ書きます。例外はありますのでご了承ください。

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?