photo credit: yllan via photopin cc
ボーノです。
クラス間でのデータのやり取りは意外と難しい。
AppDelegateを使うと、わりと感覚的に、且つシンプルに実装できる。 更には、この方法はクラス同士が親子関係になくても使えるので便利。
クラス間でデータをやり取りする方法
簡単に言うと、AppDelegateクラスを仲介させて、データの受け渡しをする。
重要な部分のみ抜粋。
まずはAppDelegateに、受け渡し用の変数の用意。
AppDelegate
AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
UIWindow *window;
NSString *title1;
NSString *body1;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) NSString *title1;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "MainViewController.h"
#import "SubViewController.h"
@implementation AppDelegate
@synthesize window;
@synthesize title1;
次に、データの受け渡し元のクラスをいじる。
ここでは、画面が消えた時にitemViewControllerのtitleを渡すようにしている。
AppDelegateのインスタンスは少し変わった作り方なので注意。
ItemViewController
ItemViewcontroller.h
#import <UIKit/UIKit.h>
@interface ItemViewController : UIViewController {
}
@end
ItemViewcontroller.m
#import "ItemViewController.h"
#import "AppDelegate.h"
- (void)viewWillDisappear:(BOOL)animated
{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate setTitle1:@"test"];
}
最後に、データの受け取り先での処理を書くだけ。
MainViewController
MainViewController.h
#import <UIKit/UIKit.h>
@interface MainViewController : UIViewController {
}
@end
MainViewController.m
#import "MainViewController.h"
#import "AppDelegate.h"
- (void)viewDidAppear:(BOOL)animated
{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSLog(delegate.title1);
}
参考サイト
下記サイトがすごい分かりやすかった。