2012/10/06

iOSアプリの画面遷移 + データの引き継ぎ(激闘編)

こんにちは。最近、本業がプチ炎上しているたーせるです。どうしてこうなったし。

閑話休題。

今日のお便りコーナーは、筑波の学園都市で暮らす ぬっくんから。

というわけで、ぬっくんが挫折したポイントに僕も挑んでみようと思います(下図は、前画面から引き継いだデータを表示するイメージです)。


あ、言い忘れましたが、ぬっくんは GUI ビルダー(Story Board)がお嫌いらしい。


ので、そこらへんも考慮して Story Board 不使用という縛りプレイで、画面遷移時のデータ引き継ぎを実装してみる事にしましょう。




【ゼロからのアプリ作成】

まずは基本中の基本、ボタンがいっこだけあるアプリから作り始めます。


Xcodeでアプリを作るときには、様々なプロジェクトの種類を選択する事ができますが、ここでは基本に忠実に、「Empty Application」を選びます。たぶんこれが知識として一番長持ちしそう。


プロジェクトを作成すると、自動的にいくつかのファイルが生成されます。

特に目に付くのが、AppDelegate.hAppDelegate.m、そして Suppoting Files ディレクトリ以下には main.m なんかもあります。

このままでは実行しても真っ白な画面しか表れないので、新たに画面表示用のクラスを追加します。

Objective-C class を選択して、


UIViewController を継承したクラスを適当に作ります。ここでは「ViewControllerA」と名付けました。


では、ViewControllerA.m を開いてプログラムを書いていきましょう。

ViewControllerA.h
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface ViewControllerA : UIViewController  
  4.   
  5. @end  

ViewControllerA.m
  1. #import "ViewControllerA.h"  
  2.   
  3. @interface ViewControllerA ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewControllerA {  
  8.     // ボタンです  
  9.     UIButton* button;  
  10. }  
  11.   
  12. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  13. {  
  14.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  15.     if (self) {  
  16.         // ボタンを初期化するよー  
  17.         button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  18.     }  
  19.     return self;  
  20. }  
  21.   
  22. - (void)viewDidLoad  
  23. {  
  24.     [super viewDidLoad];  
  25.  // Do any additional setup after loading the view.  
  26.       
  27.     button.frame = CGRectMake(0.0, 160.0, 320.0, 40.0);  
  28.     [button setTitle:@"こんにちはボタン" forState:UIControlStateNormal];  
  29.     [button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];  
  30.     [self.view addSubview:button];  
  31. }  
  32.   
  33. - (void)action  
  34. {  
  35.     NSLog(@"ボタンが押されました");  
  36. }  
  37.   
  38. - (void)didReceiveMemoryWarning  
  39. {  
  40.     [super didReceiveMemoryWarning];  
  41.     // Dispose of any resources that can be recreated.  
  42. }  
  43.   
  44. @end  

あとは、アプリを起動したときに ViewControllerA の内容が表示されるよう、AppDelegate.m も少しいじります。

AppDelegate.h
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface AppDelegate : UIResponder <UIApplicationDelegate>  
  4.   
  5. @property (strong, nonatomic) UIWindow *window;  
  6.   
  7. @end  

AppDelegate.m
  1. #import "AppDelegate.h"  
  2.   
  3. // 初期画面となるVCのヘッダファイルをインポート  
  4. #import "ViewControllerA.h"  
  5.   
  6. @implementation AppDelegate {  
  7.     // 初期画面用のビューコントローラ  
  8.     UIViewController* viewController;  
  9. }  
  10.   
  11. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  12. {  
  13.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
  14.     // Override point for customization after application launch.  
  15.     self.window.backgroundColor = [UIColor whiteColor];  
  16.       
  17.     // 初期画面をてきとうに作るよー!!  
  18.     viewController = [[ViewControllerA alloc] init];  
  19.     [self.window addSubview:viewController.view];  
  20.       
  21.     [self.window makeKeyAndVisible];  
  22.     return YES;  
  23. }  
  24.   
  25. @end  

これでよし。ビルドしてみると、ボタンの一個ついたアプリが完成しました。やったね。さっそく売ろう。

……というのは冗談です。



【画面遷移を実現しよう】

画面遷移を実現するために、UIKit には様々なクラスが用意されていますが、今回は、UINavigationController クラスを使って画面遷移を実現しています。もちろん Story Board は使いません。

完成イメージとしては、ボタンを押すごとに、下図の左右の画面が相互に遷移する感じです。しゅごい。
 

画面遷移なので、画面クラスも複数必要になります。

先ほどと同じ要領で、「ViewControllerB」というクラスを追加しましょう。

で、各実装ファイルのソースコードを以下のように書き換えます(ヘッダファイルはそのままでOK)。

AppDelegate.m
  1. #import "AppDelegate.h"  
  2.   
  3. // 初期画面となるVCのヘッダファイルをインポート  
  4. #import "ViewControllerA.h"  
  5.   
  6. @implementation AppDelegate {  
  7.     // 初期画面用のビューコントローラ  
  8.     UIViewController* viewController;  
  9.       
  10.     // 画面遷移用のナビゲーションコントローラ  
  11.     UINavigationController* navigationController;  
  12. }  
  13.   
  14. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  15. {  
  16.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
  17.     // Override point for customization after application launch.  
  18.     self.window.backgroundColor = [UIColor whiteColor];  
  19.       
  20.     // 初期画面をてきとうに初期化するよー!!  
  21.     viewController = [[ViewControllerA alloc] init];  
  22.     navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];  
  23.       
  24.     [self.window addSubview:navigationController.view];  
  25.     [self.window bringSubviewToFront:viewController.view];  
  26.       
  27.     [self.window makeKeyAndVisible];  
  28.     return YES;  
  29. }  
  30.   
  31. @end  

ViewControllerA.m
  1. #import "ViewControllerA.h"  
  2.   
  3. // 遷移先の画面となるVCのヘッダファイルもインポート  
  4. #import "ViewControllerB.h"  
  5.   
  6. @interface ViewControllerA ()  
  7.   
  8. @end  
  9.   
  10. @implementation ViewControllerA {  
  11.     UIButton* button;  
  12. }  
  13.   
  14. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  15. {  
  16.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  17.     if (self) {  
  18.         // Custom initialization  
  19.     }  
  20.     return self;  
  21. }  
  22.   
  23. - (void)viewDidLoad  
  24. {  
  25.     [super viewDidLoad];  
  26.     // Do any additional setup after loading the view.  
  27.       
  28.     button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  29.     button.frame = CGRectMake(0.0, 160.0, 320.0, 40.0);  
  30.     [button setTitle:@"こんにちはボタン" forState:UIControlStateNormal];  
  31.     [button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];  
  32.     [self.view addSubview:button];  
  33. }  
  34.   
  35. - (void)action  
  36. {  
  37.     NSLog(@"ボタンが押されました");  
  38.       
  39.     // 次画面を指定して遷移  
  40.     ViewControllerB* nextViewController = [[ViewControllerB alloc] init];  
  41.     if(nextViewController) {  
  42.         [self.navigationController pushViewController:nextViewController animated:YES];  
  43.     }  
  44. }  
  45.   
  46. - (void)didReceiveMemoryWarning  
  47. {  
  48.     [super didReceiveMemoryWarning];  
  49.     // Dispose of any resources that can be recreated.  
  50. }  
  51.   
  52. @end  

ViewControllerB.m
  1. #import "ViewControllerB.h"  
  2.   
  3. @interface ViewControllerB ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewControllerB {  
  8.     UIButton* button;  
  9. }  
  10.   
  11. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  12. {  
  13.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  14.     if (self) {  
  15.         // Custom initialization  
  16.     }  
  17.     return self;  
  18. }  
  19.   
  20. - (void)viewDidLoad  
  21. {  
  22.     [super viewDidLoad];  
  23.  // Do any additional setup after loading the view.  
  24.       
  25.     button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  26.     button.frame = CGRectMake(0.0, 160.0, 320.0, 40.0);  
  27.     [button setTitle:@"こんにちはボタン2" forState:UIControlStateNormal];  
  28.     [button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];  
  29.     [self.view addSubview:button];  
  30. }  
  31.   
  32. - (void)action  
  33. {  
  34.     // さっきの画面に戻るよー  
  35.     [self.navigationController popViewControllerAnimated:YES];  
  36. }  
  37.   
  38. - (void)didReceiveMemoryWarning  
  39. {  
  40.     [super didReceiveMemoryWarning];  
  41.     // Dispose of any resources that can be recreated.  
  42. }  
  43.   
  44. @end  

ここまでは、実は Story Board を使えば割と一瞬で作れるのですが。



【いよいよデータの受け渡し】

まずは基本となる実装方針のご紹介。

僕だったらこうする、というアイディアをらくがきにしてみました。


つまり、共有データをアプリ内の一箇所にまとめてしまい、画面のみなさんは好きなときにそれを参照するのです。

さすがにここまでの前置きが長すぎて、読む方もだいぶ疲れた頃だと思うので、このへんで本日の最終成果を載せておきましょう。

 
  

ちょっと見づらいですが、ボタンのテキストが前の画面のデータを引きずってきて、未練がましく表示するサンプルです。

ちなみにここで使用する「共有データ置き場」はインスタンスとして実現できますが、「アプリ内にひとつだけ」という制約を設ける必要があります。

ご存知の方も多いかと思いますが、Singleton パターンが使えそうですね。

というわけで、まずは共有データ置き場のコードを書いてみます。

SharedData.h
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface SharedData : NSObject  
  4. + (id)instance;  
  5.   
  6. // データをキーとともに追加します  
  7. - (void)setData:(id)anObject forKey:(id) aKey;  
  8.   
  9. // 指定したキーに対応するデータを返します  
  10. - (id)getDataForKey:(id)aKey;  
  11.   
  12. // 指定したキーと、それに対応するデータを、辞書から削除します  
  13. - (void)removeDataForKey:(id)aKey;  
  14.   
  15. @end  

SharedData.m
  1. #import "SharedData.h"  
  2.   
  3. @implementation SharedData {  
  4.     NSMutableDictionary* dictionary;  
  5. }  
  6. // 初期化  
  7. - (id)init  
  8. {  
  9.     self =  [super init];  
  10.     if(self) {  
  11.         dictionary = [[NSMutableDictionary alloc] init];  
  12.     }  
  13.     return self;  
  14. }  
  15.   
  16. // インスタンスの取得(外部のクラスからはこちらを呼ぶ)  
  17. + (id)instance  
  18. {  
  19.     static id _instance = nil;  
  20.     @synchronized(self) {  
  21.         if(!_instance) {  
  22.             _instance = [[self alloc] init];  
  23.         }  
  24.     }  
  25.     return _instance;  
  26. }  
  27.   
  28. // データをキーとともに追加します  
  29. - (void)setData:(id) anObject forKey:(id) aKey  
  30. {  
  31.     @synchronized(dictionary) {  
  32.         [dictionary setObject:anObject forKey:aKey];  
  33.     }  
  34. }  
  35.   
  36. // 指定したキーに対応するデータを返します  
  37. - (id)getDataForKey:(id)aKey  
  38. {  
  39.     id retval = [dictionary objectForKey:aKey];  
  40.     return retval != [NSNull null] ? retval : nil;  
  41. }  
  42.   
  43. // 指定したキーと、それに対応するデータを、辞書から削除します  
  44. - (void)removeDataForKey:(id)aKey  
  45. {  
  46.     @synchronized(dictionary) {  
  47.         [dictionary removeObjectForKey:aKey];  
  48.     }  
  49. }  
  50.   
  51. @end  

データ置き場は、NSMutableDictionary のインスタンスを内包しており、「キー(識別子)」を用いて参照できるようにしてあります。意味のあるデータ集合を、識別子とともに格納する事により、DTO のように振る舞う事ができます。

続いて、共有データを参照できるよう、各ビューコントローラクラスを以下のように書き換えます。

ViewControllerA.m
  1. #import "ViewControllerA.h"  
  2. #import "ViewControllerB.h"  
  3.   
  4. // 共有データ置き場のヘッダファイルをインポート  
  5. #import "SharedData.h"  
  6.   
  7. @interface ViewControllerA ()  
  8.   
  9. @end  
  10.   
  11. @implementation ViewControllerA {  
  12.       
  13.     // 共有データ置き場へのポインタ  
  14.     SharedData* sharedData;  
  15.       
  16.     UIButton* button;  
  17. }  
  18.   
  19. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  20. {  
  21.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  22.     if (self) {  
  23.           
  24.         // 共有データインスタンスを取得  
  25.         sharedData = [SharedData instance];  
  26.     }  
  27.     return self;  
  28. }  
  29.   
  30. - (void)viewDidLoad  
  31. {  
  32.     [super viewDidLoad];  
  33.     // Do any additional setup after loading the view.  
  34.       
  35.     button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  36.     button.frame = CGRectMake(0.0, 160.0, 320.0, 40.0);  
  37.     [button setTitle:@"こんにちはボタン" forState:UIControlStateNormal];  
  38.     [button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];  
  39.     [self.view addSubview:button];  
  40. }  
  41.   
  42. - (void)action  
  43. {  
  44.     NSLog(@"ボタンが押されました");  
  45.       
  46.     // 共有データにメッセージをセットして遷移  
  47.     [sharedData setData:@"これは、初期画面の遺言です" forKey:@"メッセージ"];  
  48.       
  49.     ViewControllerB* nextViewController = [[ViewControllerB alloc] init];  
  50.     if(nextViewController) {  
  51.         [self.navigationController pushViewController:nextViewController animated:YES];  
  52.     }  
  53. }  
  54.   
  55. // 別の画面から遷移してきたとき  
  56. - (void)viewWillAppear:(BOOL)animated  
  57. {  
  58.     // 共有データからデータを読み出し  
  59.     NSString* message = [sharedData getDataForKey:@"メッセージ"];  
  60.     if(message != nil) {  
  61.         // データがあればボタンのタイトルを書き換え  
  62.         [button setTitle:message forState:UIControlStateNormal];  
  63.     }  
  64. }  
  65.   
  66. - (void)didReceiveMemoryWarning  
  67. {  
  68.     [super didReceiveMemoryWarning];  
  69.     // Dispose of any resources that can be recreated.  
  70. }  
  71.   
  72. @end  

ViewControllerB.m
  1. #import "ViewControllerB.h"  
  2.   
  3. // 共有データ置き場のヘッダファイルをインポート  
  4. #import "SharedData.h"  
  5.   
  6. @interface ViewControllerB ()  
  7.   
  8. @end  
  9.   
  10. @implementation ViewControllerB {  
  11.     // 共有データ置き場へのポインタ  
  12.     SharedData* sharedData;  
  13.       
  14.     UIButton* button;  
  15. }  
  16.   
  17. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  18. {  
  19.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  20.     if (self) {  
  21.   
  22.         // 共有データインスタンスを取得  
  23.         sharedData = [SharedData instance];  
  24.     }  
  25.     return self;  
  26. }  
  27.   
  28. - (void)viewDidLoad  
  29. {  
  30.     [super viewDidLoad];  
  31.  // Do any additional setup after loading the view.  
  32.       
  33.     button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  34.     button.frame = CGRectMake(0.0, 160.0, 320.0, 40.0);  
  35.     [button setTitle:@"こんにちはボタン2" forState:UIControlStateNormal];  
  36.     [button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];  
  37.     [self.view addSubview:button];  
  38. }  
  39.   
  40. - (void)action  
  41. {  
  42.     // 共有データに書き込んでさっきの画面に戻るよー  
  43.     [sharedData setData:@"これは、画面2の遺言です" forKey:@"メッセージ"];  
  44.     [self.navigationController popViewControllerAnimated:YES];  
  45. }  
  46.   
  47. // 別の画面から遷移してきたとき  
  48. - (void)viewWillAppear:(BOOL)animated  
  49. {  
  50.     // 共有データからデータを読み出し  
  51.     NSString* message = [sharedData getDataForKey:@"メッセージ"];  
  52.     if(message != nil) {  
  53.         // データがあればボタンのタイトルを書き換え  
  54.         [button setTitle:message forState:UIControlStateNormal];  
  55.     }  
  56. }  
  57.   
  58. - (void)didReceiveMemoryWarning  
  59. {  
  60.     [super didReceiveMemoryWarning];  
  61.     // Dispose of any resources that can be recreated.  
  62. }  
  63.   
  64. @end  

…残りのAppDelegateクラスや各種ヘッダファイルはそのままで OK。

これを実行すると、前画面が今際のきわに遺したメッセージを、遷移先がきちんと受け継いで表示している事が分かります。やったね。

というわけで、ぬっくんはがんばれ。

2 件のコメント:

  1. お疲れ様です(*´ω`*)
    AppDelegateまわりの記述も結構手こずった記憶があったのでこれ見て復習してみます!

    返信削除
  2. コメントありがとうございます。

    実は、AppDelegateクラスには「Template Methodパターン」というデザインパターンの一種が使われています(たぶん)。

    最初は、「なんでそんなややこしいことを!!」と思われるかも知れませんが、プログラマがやる事は「オーバーライドメソッドの中身を埋めるだけ」です。これらのメソッドは自動的に呼び出されます。

    ふつうのプログラムが「自由記述問題」ならば、Template Methodは「穴埋め問題」のようなもので、慣れてくると解答スピードが上がる、もとい生産性が向上するので、様々なところで活用されているパターンです(Java ServletやProcessingなど…)。

    ですので、ここでいくつかのデザインパターンを身につけておくと、他の環境でオブジェクト指向プログラミングをするときにもラクになれます。

    【おすすめ書籍】

    ・ 荻原剛志 『詳解Objective-C 2.0 第3版』

    ・ 所友太 『iPhoneプログラミング UIKit 詳解リファレンス』
    ⇒ Story Boardを使わずに画面まわりを作りたい人に

    ・ 木下誠 『Dynamic Objective-C』
    ⇒ GoFのデザインパターンをObjective-Cで解説しています

    3冊目はちょっと難易度が高めなので、難しく感じる場合は、結城さんの『増補改訂版 Java言語で学ぶデザインパターン入門』を先に読むとよいと思います。

    返信削除

ひとことどうぞφ(・ω・,,)