I would recommend against using NSUserDefaults
as you do not need persistent behavior, you want to handle messaging between 2 objects. NSUserDefaults are designed to support customization based on a user's preferences. See the snippet from the documentation below.
I would recommend delegation as it is a design pattern used throughout Apple's code and would be very beneficial for you to know well!
The NSUserDefaults class provides a programmatic interface for
interacting with the defaults system. The defaults system allows an
application to customize its behavior to match a user’s preferences.
For example, you can allow users to determine what units of
measurement your application displays or how often documents are
automatically saved. Applications record such preferences by assigning
values to a set of parameters in a user’s defaults database. The
parameters are referred to as defaults since they’re commonly used to
determine an application’s default state at startup or the way it acts
by default.
There are a number of ways of going this.
Create a weak instance variable in the second view that references the first view and use that to get the data to the first view: weak ViewController* firstView
. Remember to add an instance variable to capture the data to firstView.
This works but introduces tight coupling between the views. They are now dependent on each other to meet the required functionality.
if (indexPath == 0) {
UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"NewView"];
MyController *myController = (MyController *)controller;
myController.firstView = self;
[self.navigationController pushViewController:controller animated:YES];
}
Use a block as a completion handler the second view can use call once the data in question has been selected. Define a block on the secondView. Now in your if statement set the completion handler block o the secondView. Now when the data is selected call the completion handler block.
Use the delegate pattern and define a delegate protocol and delegate property for secondView. The firstView will implement the delegate protocol. So when the data is collected you would call in the secondView.
[delegate SecondViewDidCollectData:myData];
Property on SecondView
@property (weak, nonatomic) id<SecondViewDelegate> delegate;
Delegate Protocol defined in SecondView header.
// define the protocol for the delegate
@protocol SecondViewDelegate
// define protocol functions that can be used in any class using this delegate
-(void)SecondViewDidCollectData:(NSData *)data;
@end