継承のお話(3) | 初心者がiPhoneアプリを作るブログ

初心者がiPhoneアプリを作るブログ

初心者がiPhoneアプリを作るブログです.
入門レベルですので開発初心者にも,できるだけ分かるように丁寧に説明していきます(多分).

それでは進めます.
前回,
「-(id)initWithFloat:(float)f String:(NSString *)str」
という関数を定義しました.

これは,私が勝手に定義した関数ですので,
MySecondClass.hをインポートしても使うことができません.

そこで,定義した関数を「.h」ファイルに記述する必要があります.
MySecondClass.hに次にように追記して下さい.
@property (unsafe_unretained, readwrite) float myFloat;


- (id)initWithFloat:(float)f String:(NSString *)str;

プロパティの宣言の下あたりに,関数を書きます.
こうすることで,このクラスのインスタンスは,この関数を使うことができるようになります.

さて,あとはAppDelegate.mに書いていきましょう.
#import "AppDelegate.h"
// 自作クラスをインポートします
#import "MySecondClass.h"


@implementation AppDelegate

@synthesize window = _window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    // MySecondClassのインスタンスを生成します.
    MySecondClass *myClass = [[MySecondClass alloc] initWithFloat:1.0 String:@"Hello"];

    
// MySecondClassのプロパティのうち,initメソッドで初期化しなかったプロパティに値をセットします
    [myClass setMyInt:3];
    
    // プロパティの値を確認します
    NSLog(@"string:%@, int:%d, float:%f", myClass.myString, myClass.myInt, myClass.myFloat);
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}


ここまで読み進めることができた人には,もう説明は不要ですよね.
クラスの継承について理解することができましたでしょうか??

ここで,少し余談なのですが,皆さんが使った事のある
UITabBarControllerはUIViewControllerを継承したものなんです.

だから何??って感じですよね,ゴメンナサイ笑

ちゃんと伝わったかどうか怪しいですが,習うより慣れろ精神で
どんどんコーディングしちゃってください.

次の記事へ

HOMEに戻る