Objective-C: How to Pass Data Between ViewControllers

By the end of this post, you will be able to pass data between ViewControllers using objective-c.

ViewControllers

  • FirstController (where the data will come from)
  • SecondController (where the data will be sent to)

First of all, we would need to have some data in the FirstController. Let’s start by creating an NSString to the FirstController.m file:

@interface FirstController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *theData = @"I am awesome";
}
@end

Now in the SecondController.h file create a property:

@interface SecondController : UIViewController
@property (strong, nonatomic) NSString *theData;
@end

Lets import the SecondController to the FirstController by adding the following above the FirstController.m:

#import "SecondController.h"

Now, let’s pass the value to the SecondController, by modifying the FirstController.m

@interface FirstController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *theData = @"I am awesome";
    SecondController *secondController = [[SecondController alloc] init];
    secondController.theData = theData; // the value has been sent to the SecondController
}
@end

This is so easy. Try it yourself and experiment!

Convert NSDate to JSON Date Format

It is often recommended to have dates formatted to JSON format when communicating with services. A JSON Date format normally looks like this:

2012-04-23T18:25:43.511Z

To Change a NSDate to JSON Date format, you can do the following:

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);

The log would show the date in JSON Date format.

Change Font Color of UIBarButtonItem

To change UIBarButtonItem Font Color, you can set the TitleTextAttributes

_createBtn = [[UIBarButtonItem alloc] initWithTitle:@"Create" style:UIBarButtonItemStylePlain target:self action:@selector(createProject)];
[_createBtn setTitleTextAttributes:[NSDictionary[UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];

The UIBarButtonItem will be changed to white by setting the [UIColor whiteColor]

NSSNumber to NSInteger and NSInteger to NSNumber in Objective C

NSNumber to NSInteger and vice versa is easy. NSInteger is a primitive type and not an object type.

To get NSInteger from a NSNumber you can do the following:

anInteger = [aNumber intValue];

To get NSInteger from a NSNumber you can do the following:

aNumber = [aNumber numberWithInteger:anInteger];