This Objective-c for iOS Cheat Sheet is written for my midterm for my Masters of Computer Science course on iOS Mobile Development. The class didn’t fill up like I thought it should. Perhaps that has to do with the fact that the class name was misspelled as ISO Mobile Development. Oops.
Creating an objective-c class
- All objects should inherit NSObject which is found in Foundation.h.
- Objects should be created in the following two files.
MyObject.h1 2 3 | #import <Foundation/Foundation.h>
@interface MyObject : NSObject
@end
|
MyObject.m1 2 3 | #import "MyObject.h"
@implementation MyObject
@end
|
Adding a local variable to an objective-c class
A variable is added to the .h file that is only used by the code in the .m file.
Person .h1 2 3 4 5 6 | #import <Foundation/Foundation.h>
@interface Person : NSObject
{
string name;
}
@end
|
Adding a property to an objective-c class
A property is a short cut for a variable wrapped in a getter and setter.
- Add an @property line in the .h file as shown below.
- Add an @synthesize line for the property in the .m file as shown below.
Person .h1 2 3 4 | #import <Foundation/Foundation.h>
@interface Person : NSObject
@property string name;
@end
|
Person .m1 2 3 4 | #import "Person.h"
@implementation Person
@synthesize name;
@end
|
Adding a method to an objective-c class
Here is an example of two methods:
- a method without a parameter
- a method with two parameters.
In many other languages, these methods signatures would look as follows:
double getPI();
double add(double x, double y);
In ojbective-c, the methods look like this:
calc.h1 2 3 4 5 | #import <Foundation/Foundation.h>
@interface calc: NSObject
-( double )getPI;
-( double )multiply:( double ) x and: ( double ) y;
@end
|
calc.m01 02 03 04 05 06 07 08 09 10 11 12 | #import "calc.h"
@implementation calc
-( double )getPI
{
return 3.14159265359;
}
-( double )multiply:( double ) x and: ( double ) y
{
return x * y;
}
@end
|
Now you call the methods different than other languages, too.
1 2 | double pi = [myCalc getPI];
[myCalc add:1 and: pi;
|
Overriding the getter for the description property
Add the following method to your .m file. Inheriting NSObject already provides the method signature so nothing needs to be added to the .h file.
1 2 3 4 | -( NSString *)description
{
return @"Your custom description here" ;
}
|
Using NSString stringWithFormat
In many languages you can write a string with tokens inside it and just replace the token. You can do this in objective-c as well.
Integer example1 2 | return [ NSString stringWithFormat: @"You have @d items in your cart." , cart.items];
|
Double example1 2 3 | return [ NSString stringWithFormat: @"Total: %.2f" , cart.Total];
|
Any object that is not a primitive, such as NSString, uses %@.
NSString example1 2 | return [ NSString stringWithFormat: @"Welcome %@" , account.username];
|
Adding a UI Element (Label, TextBox, Button)
- You use the UI editor to add an the elements to the UI.
- Then you create a variable for each element.
- Then you link the field to the element in the xib.
PersonViewController.h1 2 3 4 5 6 7 8 | #import <Foundation/Foundation.h>
@interface PersonViewController: UIViewController
{
IBOutlet UILabel *nameLabel;
IBOutlet UITextField *nameTextField;
IBOutlet UIButton *submitNameButton;
}
@end
|
PersonViewController.m1 2 3 | #import "PersonViewController.h"
@implementation PersonViewController
@end
|
Notice nothing is in the .m file. Of course, you could add these variables as properties and then you would an @synthesize call for these variables in the .m file.
Adding an event for clicking a button
This is pretty much the same as adding a method to an objective-c class. The only difference is you attach this method to a button in the xib.
Note: The button variable doesn’t really matter, it can by a property or just a member.
PersonViewController.h1 2 3 4 5 | #import <Foundation/Foundation.h>
@interface PersonViewController: UIViewController
@property ( nonatomic ) IBOutlet UIButton *submitNameButton;
-( IBAction )buttonPressed:( id )sender;
@end
|
PersonViewController.m1 2 3 4 5 6 7 | #import "PersonViewController.h"
@implementation PersonViewController
-( IBAction )buttonPressed:( id )sender
{
}
@end
|
Wrap a ViewController in a UINavigationController
In AppDelegate.m, change the default application method to look as follows:
01 02 03 04 05 06 07 08 09 10 11 | - ( BOOL )application:(UIApplication *)application didFinishLaunchingWithOptions:( NSDictionary *)launchOptions
{
self .window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ViewController *viewController = [[ViewController alloc] initWithNibName: @"ViewController" bundle: nil ];
UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController: viewController];
self .window.rootViewController = navCtrl;
[ self .window makeKeyAndVisible];
return YES ;
}
|
Add Buttons to the top bar (UIBar)
1 2 3 4 5 6 7 | UIBarButtonItem * rightBarButton = [[UIBarButtonItem alloc]initWithTitle: @"Summary" style:UIBarButtonItemStyleBordered target: self action: @selector (summaryButton:)];
self .navigationItem.rightBarButtonItem = rightBarButton;
UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithTitle: @"Map" style:UIBarButtonItemStyleBordered target: self action: @selector (mapButton:)];
self .navigationItem.leftBarButtonItem = leftBarButton;
|
Launch a ViewController
If you have a UIViewController called MapViewController, you can launch it as follows.
1 2 | MapViewController *mapVC = [[MapViewController alloc] initWithNibName: @"MapViewController" bundle: nil ];
[[ self navigationController] pushViewController:mapVC animated: YES ];
|
Launch a ViewController and pass it data using a property
This passes a property called database into the SummaryViewController.
1 2 3 | SummaryViewController *summaryVC = [[SummaryViewController alloc] initWithNibName: @"SummaryViewController" bundle: nil ];
summaryVC.database = self .database;
[[ self navigationController] pushViewController:summaryVC animated: YES ];
|
Other ways to pass it a property include:
- Using a custom init method such as initWithDatabase.
- Using a segue.
Get current date and time as string
1 2 3 4 5 6 7 8 | NSString * currentTimeAsString()
{
NSDate *date = [ NSDate date];
NSDateFormatter *dateFormat = [[ NSDateFormatter alloc]init];
[dateFormat setDateFormat: @"d MMM YYYY, h:mm a" ];
NSString *dateString = [dateFormat stringFromDate:date];
return dateString;
}
|
Using a UITabBarController
Change the application method in the AppDelegate.m file.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | - ( BOOL )application:(UIApplication *)application didFinishLaunchingWithOptions:( NSDictionary *)launchOptions
{
self .window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UITabBarController *tabBarController = [[UITabBarController alloc] init];
UIViewController *mileageView = [[MileageViewController alloc] init];
UIViewController *mapView = [[MapViewController alloc] init];
NSArray *controllers = [ NSArray arrayWithObjects:mileageView, mapView, nil ];
[tabBarController setViewControllers:controllers];
self .window.rootViewController = tabBarController;
[ self .window makeKeyAndVisible];
return YES ;
}
|
Add image to TabBarItem
In the ViewController that is added as part of an array to the TabBarItem, override the iniWithNibName method as follows:
01 02 03 04 05 06 07 08 09 10 11 | - ( id )initWithNibName:( NSString *)nibNameOrNil bundle:( NSBundle *)nibBundleOrNil
{
self = [ super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if ( self )
{
UITabBarItem *tbi = [ self tabBarItem];
tbi.Title = @"Contacts" ;
tbi.Image = [UIImage imageNamed: @"Contact-image.png" ];
}
return self ;
}
|
Map
01 02 03 04 05 06 07 08 09 10 11 12 | Change the map view type.
-( IBAction ) changeMap
{
if (mapView.mapType == MKMapTypeStandard)
{
mapView.mapType = MKMapTypeSatellite;
}
else
{
mapView.mapType = MKMapTypeStandard;
}
}
|
Update the user location on a map.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 | -( void )mapView:(MKMapView *)map didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region;
coord = userLocation.coordinate;
region = MKCoordinateRegionMakeWithDistance(coord, START_LATITUDE_SIZE, START_LONGITUDE_SIZE);
[mapView setRegion:region animated: YES ];
}
- ( void )didReceiveMemoryWarning
{
[ super didReceiveMemoryWarning];
}
|
TextBox resignFirstResponder
How to sort an NSArray
http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/sortedArrayHint
Categories (iOS version of Extension Methods in C#)
If an object is missing a method you think it should just have, such as NSDate returning the date in a specified format, you can simply create that method as follows and then use it anywhere you import the .h file.
DateExtension.h1 2 3 4 | #import <Foundation/Foundation.h>
@interface NSDate (DateExtender)
-( NSString *)getDateWithFormat:( NSString *)format;
@end
|
DateExtension.m1 2 3 4 5 6 7 8 9 | #import "DateExtender.h"
@implementation NSDate (DateExtender)
-( NSString *)getDateWithFormat:( NSString *)format
{
NSDateFormatter *dateFormat = [[ NSDateFormatter alloc]init];
[dateFormat setDateFormat:format];
return [dateFormat stringFromDate: self ];
}
@end
|
Notice the class name is the same as the object you wish to extend: NSDate.
Notice there is a group name in paranthesis.
UITable
NSTimer
see Notice project.
Use a plist
see car project.