Passing Data Between View Controllers
Passing data between view controllers is a common requirement in iOS app development. It involves transferring data from one view controller to another, allowing the receiving view controller to access and use that data.
Method 1: Using a Segue
A common way to pass data between view controllers is by using segues. Segues define a transition between two view controllers in a storyboard. Here's how you can do it:
- Declare a property in the destination view controller to hold the data.
@interface DestinationViewController : UIViewController
@property (nonatomic, strong) NSString *dataToPass;
@end
- Implement the
prepareForSegue:sender:
method in the source view controller.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"mySegue"]) {
DestinationViewController *destVC = segue.destinationViewController;
destVC.dataToPass = @"Hello, World!";
}
}
- In your storyboard, create a segue between the two view controllers and give it an identifier.
Method 2: Using a Delegate
Another way to pass data between view controllers is by using a delegate. A delegate is an object that acts on behalf of another object.
- Create a protocol in the source view controller specifying the methods that the delegate should implement.
@protocol DataPassDelegate <NSObject>
- (void)dataDidPass:(NSString *)data;
@end
- Declare a property in the source view controller to hold a delegate object.
@interface SourceViewController : UIViewController
@property (nonatomic, weak) id<DataPassDelegate> delegate;
@end
- In the source view controller, call the delegate method to pass the data.
if ([self.delegate respondsToSelector:@selector(dataDidPass:)]) {
[self.delegate dataDidPass:@"Hello, World!"];
}
- In the destination view controller, implement the delegate method to receive the data.
- (void)dataDidPass:(NSString *)data {
NSLog(@"%@", data);
}
Method 3: Using Singleton
A third approach to passing data between view controllers is by using a singleton. A singleton is a class that allows only one instance of itself to be created.
- Create a singleton class in which you can store and access the data.
@interface DataManager : NSObject
@property (nonatomic, strong) NSString *data;
+ (instancetype)sharedManager;
@end
@implementation DataManager
+ (instancetype)sharedManager {
static DataManager *shared = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shared = [[self alloc] init];
});
return shared;
}
@end
- Set the data in the singleton class in the source view controller.
[[DataManager sharedManager] setData:@"Hello, World!"];
- Get the data from the singleton class in the destination view controller.
NSString *data = [[DataManager sharedManager] data];
NSLog(@"%@", data);
These are just a few methods to pass data between view controllers in iOS. Each method has its own advantages and use cases, so choose the one that best fits your app's needs.