photo credit: yllan via photopin cc
Bono.
Exchanging data between classes is surprisingly difficult.
Using AppDelegate is rather sensible and simple to implement. Furthermore, this method is convenient because it can be used even if the classes are not in a parent-child relationship.
コンテンツ
How to exchange data between classes
Simply put, the AppDelegate class is used as an intermediary to pass data.
Excerpts from important parts only.
First, in AppDelegate, prepare variables for passing on.
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;
Next, tweak the class from which data is passed.
Here, the title of the itemViewController is passed when the screen disappears.
Note that the AppDelegate instance is created in a slightly different way.
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"];
}
Finally, simply write the process at the destination of the data.
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);
}
Reference Site
The following site was incredibly easy to understand.
[XCode]How to pass values between views that are not parent-child relationships | Exception Code.