iphone ios - Great UIKit/Objective-C code snippets

framework views (5)

Save bool to User Defaults

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Yes Bool"];

Copy a file from x to y

[[NSFileManager defaultManager] copyItemAtPath:x toPath:y error:nil];

Display a new view

[self presentModalViewController:(UIViewController *) animated:YES];

Screen touches method

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {}

Get documents directory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

Load URL

[MyWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://couleeapps.hostei.com"]]];  

Get Current Date and time:

NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];

Own enum type:

typedef enum {
    a = 0, b = 1, c = 2
} enumName;

Quartz draw arc

CGContextRef ctxt = UIGraphicsGetCurrentContext();
CGContextAddArc(ctxt, x, y, radius, startDeg, endDeg);

New to Objective-C iPhone/iPod touch/iPad development, but I'm starting to discover lots of power in one-liners of code such as this:

[UIApplication sharedApplication].applicationIconBadgeNumber = 10;

Which will display that distinctive red notification badge on your app iphone with the number 10.

Please share you favorite one or two-liners in Objective-C for the iPhone/iPod touch/iPad here. PUBLIC APIs ONLY.

  1. Display an alert window:

    UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"too many alerts" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [alert show] 
  2. Get the path to the Documents folder:

    NSArray*  paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString* documentsDirectory = [paths objectAtIndex:0];
  3. Push another view controller onto the Navigation Bar:

    [self.navigationController pushViewController:anotherVC animated:YES];
  4. Fade away a UIView by animating the alpha down to 0:

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1];  // fade away over 1 seconds
    [aView setAlpha:0]; 
    [UIView commitAnimations];                      
  5. Get the name of the app

    self.title = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  6. Change the status bar to black

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
  7. Change the style of the navigation bar (from in a view controller):

    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
  8. Save a NSString into NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:loginName forKey:kUserLoginName];
  9. Get an NSString from NSUserDefaults:

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];

    NSString* loginName = [defaults stringForKey:kUserLoginName];

  10. Check to make sure an objects support a method before calling it:

    if ([item respondsToSelector:@selector(activateBOP:)]) {
        [item activateBOP:closeBOP];
  11. Log the name of the class and function:

    NSLog(@"%s", __PRETTY_FUNCTION__);
  12. Add rounded corners and/or a border around any UIView item (self)

    self.layer.borderColor  = [UIColor whiteColor].
    self.layer.cornerRadius = 8;     // rounded corners
    self.layer.masksToBounds = YES;  // prevent drawing outside border
  13. Open Google Maps app with directions between two lat/long points

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f&dirflg=d", start.latitude, start.longitude, finish.latitude, finish.longitude];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]]; 

Open an URL in Safari

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com/"]];

Hide the status bar

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];

Dial a Phone Number (iPhone Only)

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://9662256888"]];

Launch the Apple Mail

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://[email protected]"]];

stop responding to touch events

[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

active the touch events

[[UIApplication sharedApplication] endIgnoringInteractionEvents];

Show the network Activity Indicator

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

Hide the network Activity Indicator

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

Prevents iPhone goes into sleep mode

[UIApplication sharedApplication].idleTimerDisabled = YES;

Make the device vibrate:


Open the Messages app with a specific phone number:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:123456789"]];

Stop responding to touch events:

[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

Start responding again:

[[UIApplication sharedApplication] endIgnoringInteractionEvents];

And finally, the single line of code browser:

[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: [urlText stringValue]]]];

NSString *result=[NSString stringWithFormat:@"%@ %@", @"Hello", @"World"];

iphone objective-c iphone-sdk-3.0 uikit