Iphone Developer Technological

Passing Data Example

Delegates or Properties, take your pick.


Class A (ViewController) wants to communicate with Class B (ViewController)

Before calling Class B, do the following:

In Class B, create a @property NSString* receivedValue;

In Class A,

#import Class B

then in the method that calls B (either prepareForSegue or didSelectRowAtIndexPath or some method where you present Class B view controller, do the following:

Class B *calledVC = alloc/init

calledVC.receivedValue = ‘whatever value you want to pass’;

then call Class B VC




Let’s say Class B wants to notify Class A that something has finished.  In Class B add this above your @interface:

@protocol YourDelegateProtocol <NSObject>

– (void)itemWillBePassed;



Then in the regular Class B @interface

@property (nonatomic, weak) id <YourDelegateProtocol> delegate;

This means that Class B has a delegate protocol declared and anyone who wants to be its delegate needs to adopt this protocol and the methods defined herein.
So now in your Class A, right on the @interface line, add <YourDelegateProtocol> right after the:

@interface ViewController : UIViewController

 And since now Class A implements Class B’s protocol, it must implement the delegate methods, which is only itemWillBePassed in our example.
Now simply, whenever Class B needs to notify Class A, it has to call:
[self itemWillBePassed];
And Class A will know about it in its implemented delegate method!
Iphone Developer Technological

Using NSUserDefaults

This is handy when saving credentials to a device so the user doesn’t have to re-login every time he launches the app. NOTE: This is not useful for saving large amounts of data or data that will change frequently. Use iCloud or persistent state stores such as databases or xml or plist files for that!

Once you have the data you wish to save somewhere in your app, call the following:

// call the store object
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// set an object for it
[prefs setObject:imageView.image forKey:@”keyToLookupImage”];
// call sync to save it
[prefs synchronize];

then later in the beginning or launch of an app you can get that data like so:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = nil;
//If myString = nil, then do all this, otherwise do nothing…
UIImage *retrievedImage = [prefs stringForKey:@”keyToLookupImage”];
imageView.image = retrievedImage;

You have just saved your user a good deal of grief and he’ll thank you for it!

Translate »