20
Objective-C and iOS SDK Quick Reference First Draft Edition Page Key • 01: Objective-C, Foundation, Properties and Collections 02: Unit Testing 03: Graphics, Drawing, and Images 04: Applications, Screens, Views, and ViewControllers 05: Gestures 06: URLs and WebViews 07: ScrollViews, TextViews, and TableViews 08: Core Data 09: Core Motion, Location & Mapping 10: Animation & Gaming 11: Media 12: Miscellaneous iPhone and iPad are trademarks of Apple Inc., registered in the U.S. and other countries. Copyright © 2011 ASAP WebSoft, LLC http://www.asapwebsoft.com/iosquickref 00.1

Ios Quick Ref

Embed Size (px)

Citation preview

Page 1: Ios Quick Ref

Objective-C and iOS SDKQuick Reference

First Draft Edition

Page Key

• 01: Objective-C, Foundation, Properties and Collections• 02: Unit Testing• 03: Graphics, Drawing, and Images• 04: Applications, Screens, Views, and ViewControllers• 05: Gestures• 06: URLs and WebViews• 07: ScrollViews, TextViews, and TableViews• 08: Core Data• 09: Core Motion, Location & Mapping• 10: Animation & Gaming• 11: Media• 12: Miscellaneous

iPhone and iPad are trademarks of Apple Inc., registered in the U.S. and other countries.

! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 00.1

Page 2: Ios Quick Ref

SDK Layers

Core OSCore ServicesMediaCocoa Touch

NSObject Introspection Methods

+isSubclassOfClass:-autorelease-class-conformsToProtocol:-description-isEqual-isKindOfClass:-isMemberOfClass:-isProxy-respondsToSelector:-performSelector:-performSelector:withObject:-performSelector:withObject:withObject:-release-retain-retainCount-self-superclass

Foundation Classes

NSObjectNSNumber NSNumberFormatter NSDecimalNumber NSDecimalNumberHandlerNS[Mutable]StringNSValue (can wrap C structs) NSValueTransformerNSDataNSMutableDataNSDate NSCalendar NSDateFormatter NSDateComponentsNSArray NSMutableArrayNSDictionary NSMutableDictionaryNSSet NSMutableSetNSDirectoryEnumeratorNSEnumeratorNSErrorNSExceptionNSNotification NSNotificationCenter NSNotificationQueueNSOperation NSInvocationOperation NSBlockOperation NSOperationQueueNSUserDefaultsNSXMLParser

NSRange Structure Members and Functions

NSUInteger lengthNSUInteger locationNSEqualRanges(range1, range2);NSLocationInRange(location, range);NSMakeRange(location, length);NSRangeFromString(string);NSStringFromRange(range);

Interface (.h) File Structure

#import <UIKit/UIKit.h>#import “SuperClassName.h” ! // if not already imported...#import “OtherHeaderName.h”

@class ClassName;! ! // forward reference for inline protocol

@protocol ProtocolName!! // optional inline protocol@protected // default@private@public@package- (DataType)methodName:(DataType)parameterName;@end

@interface ClassName : SuperClassName <ProtocolName[, ...]>{! DataType variableName;}@property (memory-mgmt-spec[, ...]) DataType propertyName;- (DataType)methodName:(DataType)parameterName;@end

Implementation (.m) File Structure

#import <UIKit/UIKit.h>#import “ClassName.h”#import “OtherHeaderName.h”

@interface ClassName(){ // if you’re not already importing the .h! DataType privateVariableName;}@property (memory-mgmt-spec[, ...]) DataType privatePropertyName;- (DataType)privateMethodName:(DataType)parameterName;@end

@implementation ClassName@synthesize propertyName[ = variableName], privatePropertyName;- (DataType)methodName:(DataType)parameterName{! // method implementation}...@end

Protocol (.h) File Structure

// Use in class interface;// or as id type qualifier, e.g., id <ProtocolName>#import <UIKit/UIKit.h>#import “OtherHeaderName.h”

@protocol ProtocolName@optional@required // default@property (memory-mgmt-spec[, ...]) DataType propertyName;- (DataType)methodName:(DataType)parameterName;@end

Objective-C, Foundation, Properties and Collections

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 01.1

Page 3: Ios Quick Ref

NSString Methods and Properties

+string+stringWithFormat:+stringWithString:-boolValue-capitalizedString-caseInsensitiveCompare:-characterAtIndex:-commonPrefixWithString:options:-compare:-componentsSeparatedByCharactersInSet:-componentsSeparatedByString:-cStringUsingEncoding:-doubleValue-enumerateLinesUsingBlock:-enumerateSubstringsInRange:options:usingBlock:-getLineStart:end:contentsEnd:forRange:-getParagraphStart:end:contentsEnd:forRange:-hasPrefix:-hasSuffix:-integerValue-intValue-isAbsolutePath-isEqualToString:-lastPathComponent-length-lineRangeForRange:-localizedCaseInsensitiveCompare:-localizedCompare:-localizedStandardCompare:-longLongValue-lowercaseString-paragraphRangeForRange:-pathComponents-pathExtension-propertyList-propertyListFromStringsFileFormat-rangeOfCharactersFromSet:-rangeOfString:-stringByAbbreviatingWithTildeInPath-stringByAddingPercentEscapesUsingEncoding:-stringByAppendingFormat:-stringByAppendingPathComponent:-stringByAppendingPathExtension:-stringByAppendingString:-stringByDeletingLastPathComponent-stringByDeletingPathExtension-stringByExpandingTildeInPath-stringByFoldingWithOptions:locale:-stringByPaddingToLength:withString:startingAtIndex:-stringByReplacingCharactersInRange:withString:-stringByReplacingOccurrencesOfString:withString:-stringByReplacingPercentEscapesUsingEncoding:-stringByResolvingSymlinksInPath-stringByStandardizingPath-stringByTrimmingCharactersInSet:-stringsByAppendingPaths:-substringFromIndex:-substringToIndex:-substringWithRange:-uppercaseString-writeToFile:atomically:encoding:error:-writeToURL:atomically:encoding:error:-sizeWithFont: // monkeypatched by UIKit-drawAtPoint:withFont:

NSMutableString Methods and Properties

+stringWithCapacity:-appendFormat:-appendString:-deleteCharactersInRange:-initWithCapacity:-insertString:atIndex:-replaceCharactersInRange:withString:-replaceOccurrencesOfString:withString:options: range:-setString:

NSString Search/Comparison Bitmask Constants (NSString.h)

NSCaseInsensitiveSearch NSDiacriticInsensitiveSearchNSLiteralSearch NSWidthInsensitiveSearchNSBackwardsSearch NSForcedOrderingSearchNSAnchoredSearch NSRegularExpressionSearchNSNumericSearch

Category Interface (.h or top of category .m) File Structure

#import “ClassName.h”

@interface ClassName (CategoryName)- (DataType)methodName:(DataType)parameterName;@end

Category Implementation (.m) File Structure

#import “ClassName.h”

@implementation ClassName (CategoryName)- (DataType)methodName:(DataType)parameterName{! // method implementation}@end

Value Types

typedef struct{! dataType variable1Name, variable2Name;} StructureDataType;

Enumeration

for (DataType *variableName in myCollection){! ...}DataType *variableName;for (variableName in myCollection){! ...}for (id key in myDictionary){! id value = [myDictionary objectForKey:key];! ...}

Objective-C, Foundation, Properties and Collections

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 01.2

Page 4: Ios Quick Ref

NSAttributedString Methods and Properties

-attribute:atIndex:effectiveRange:-attribute:atIndex:longestEffectiveRange:inRange:-attributedSubstringFromRange:-attributesAtIndex:effectiveRange:-attributesAtIndex:longestEffectiveRange:inRange:-enumerateAttribute:inRange:options:usingBlock:-enumerateAttributesInRange:options:usingBlock:-initWithAttributedString:-initWithString:-initWithString:attributes:-isEqualToAttributedString:-length-string

NSCharacterSet Methods and Properties

+alphanumericCharacterSet+capitalizedLetterCharacterSet+characterSetWithBitmapRepresentation:+characterSetWithCharactersInString:+characterSetWithContentsOfFile:+characterSetWithRange:+controlCharacterSet+decimalDigitCharacterSet+letterCharacterSet+lowercaseLetterCharacterSet+newlineCharacterSet+nonBaseCharacterSet+punctuationCharacterSet+symbolCharacterSet+uppercaseLetterCharacterSet+whitespaceAndNewlineCharacterSet+whitespaceCharacterSet-bitmapRepresentation-characterIsMember:-hasMemberInPlane:-invertedSet-isSupersetOfSet:-longCharacterIsMember:

NSScanner Methods and Properties

+localizedScannerWithString:+scannerWithString:-isAtEnd-scanCharactersFromSet:intoString:-scanDecimal:-scanDouble:-scanFloat:-scanHexDouble:-scanHexInt:-scanHexLongLong:-scanInt:-scanInteger:-scanLocation-scanLongLong:-scanString:intoString:-scanUpToCharactersFromSet:intoString:-scanUpToString:intoString:-setCaseSensitive:-setCharactersToBeSkipped:-setLocale:-setScanLocation:-string

NSAttributedString Bitmask Constants (NSAttributedString.h)

NSAttributedStringEnumerationReverseNSAttributedStringEnumerationLongestEffectiveRangeNotRequired

NSCharacterSet Constants (NSCharacterSet.h)

NSOpenStepUnicodeReservedBase

General Memory Management Best Practices

• Invoking alloc, copy, or new means I own it, so decide where to release it and implement immediately.

• Release instance variables in dealloc.• Release a local variable before the end of the method, as soon as possible once it’s no

longer needed.• Autorelease local variables that are to be returned from a method; for example:return [result autorelease];

• Be careful that you don’t incur memory leaks when you set the same variable multiple times in your code; don’t assign an instance variable without releasing the old value, or use retained properties and dot notation to automatically release old versions when assigning new values (but you still have to release it in dealloc!!!).

• Use immutable values wherever you can.• Use methods other than alloc, copy, or new when appropriate, i.e. autoreleased objects

(but don’t abuse autorelease, e.g., by creating thousands of objects in an inner loop where a mutable object would make more sense).

Class Initializers

- (id)init{! if [self = [super init]]! {! ! // initialize subclass instance here! }! return self;}// Don’t call init twice...- (id)initWithValidOperations:(NSSet *)aSet{! self = [self init];! self.validOperations = aSet; // no-op if self == nil! return self;}// Another example if the additional initializer is required...- (id)init{! return nil;}

View-to-Controller Communication

Target-Action DelegationData Source Protocol

Model-to-Controller Communication

Notification (broadcast) Key-Value Observing (KVO)

Objective-C, Foundation, Properties and Collections

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 01.3

Page 5: Ios Quick Ref

NSArray Methods

+array+arrayWithArray:+arrayWithContentsOfFile:+arrayWithContentsOfURL:+arrayWithObject:+arrayWithObjects:-addObserver:forKeyPath:options:context:-addObserver:toObjectsAtIndexes:forKeyPath: options:context:-arrayByAddingObject:-arrayByAddingObjectsFromArray:-componentsJoinedByString:-containsObject:-count-firstObjectCommonWithArray:-isEqualToArray:-filteredArrayUsingPredicate:-getObjects:range:-indexOfObject:-indexOfObject:inRange:-indexOfObject:inSortedRange:options: usingComparator:-indexOfObjectAtIndexes:options:passingTest:-indexOfObjectIdenticalTo:-indexOfObjectIdenticalTo:inRange:-indexOfObjectPassingTest:-indexOfObjectWithOptions:passingTest:-initWithArray:copyItems:-isEqualToArray:-lastObject // returns nil on empty arrays-makeObjectsPerformSelector:-makeObjectsPerformSelector:withObject:-objectAtIndex:-objectsAtIndexes:-pathsMatchingExtensions:-removeObserver:forKeyPath:-removeObserver:fromObjectsAtIndexes:forKeyPath:-setValue:forKey:-sortedArrayUsingFunction:context:-sortedArrayUsingDescriptors:-sortedArrayUsingSelector:-sortedArrayUsingComparator:-sortedArrayWithOptions:usingComparator:-subarrayWithRange:-valueForKey:

NSMutableArray Methods

-addObject:-addObjectsFromArray:-exchangeObjectAtIndex:withObjectAtIndex:-filterUsingPredicate:-insertObject:atIndex:-insertObjects:atIndexes:-removeAllObjects-remoteLastObject-removeObject:-removeObject:inRange:-removeObjectAtIndex:-removeObjectsAtIndexes:-removeObjectIdenticalTo:-removeObjectIdenticalTo:inRange:-removeObjectsInArray:-removeObjectsInRange:-replaceObjectAtIndex:withObject:-replaceObjectsAtIndexes:withObjects:-replaceObjectsInRange:withObjectsFromArray:range:-replaceObjectsInRange:withObjectsFromArray:-setArray:-sortUsingDescriptors:-sortUsingComparator:-sortWithOptions:usingComparator:-sortUsingFunction:context:-sortUsingSelector:

NSBinarySearchingOptions Bitmask Constants (NSArray.h)

NSBinarySearchingFirstEqual NSBinarySearchingInsertionIndexNSBinarySearchingLastEqual

Objective-C, Foundation, Properties and Collections

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 01.4

Page 6: Ios Quick Ref

NSDictionary Methods

+dictionary+dictionaryWithContentsOfFile:+dictionaryWithContentsOfURL:+dictionaryWithDictionary:+dictionaryWithObject:forKey:+dictionaryWithObjects:forKeys:+dictionaryWithObjectsAndKeys:-allKeys-allKeysForObject:-allValues-count-descriptionInStringsFileFormat-initWithDictionary:-initWithDictionary:copyItems:-isEqualToDictionary:-keysOfEntriesPassingTest:-keysSortedByValueUsingComparator:-keysSortedByValueUsingSelector:-objectForKey:-objectsForKeys:notFoundMarker:-valueForKey:-writeToFile:atomically:-writeToURL:atomically:

NSMutableDictionary Methods

-addEntriesFromDictionary:-removeAllObjects-removeObjectForKey:-removeObjectsForKeys:-setDictionary:-setObject:forKey:-setValue:forKey:

NSSet Methods

+set+setWithArray:+setWithObject:+setWithObjects:+setWithSet:-addObserver:forKeyPath:options:context:-allObjects-anyObject-containsObject:-count-filteredSetUsingPredicate:-initWithSet:copyItems:-intersectsSet:-isEqualToSet:-isSubsetOfSet:-makeObjectsPerformSelector:-makeObjectsPerformSelector:withObject:-member:-objectsPassingTest:-removeObserver:forKeyPath:-setByAddingObject:-setByAddingObjectsFromArray:-setByAddingObjectsFromSet:-setValue:forKey:-sortedArrayUsingDescriptors:-valueForKey:

NSMutableSet Methods

-addObject:-addObjectsFromArray:-filterUsingPredicate:-intersectSet:-minusSet:-removeObject:-removeAllObjects-setSet:-unionSet:

@synthesized (atomic retain) accessor implementation

- (DataType)propertyName{! [_internal lock];! id result = [[propertyVariableName retain] autorelease];! [_internal unlock];! return result;}

@synthesized (atomic copy) accessor implementation

- (DataType)propertyName{! [_internal lock];! id result = [[propertyVariableName copy] autorelease];! [_internal unlock];! return result;}

@synthesized (nonatomic or assign) accessor implementation

- (DataType)propertyName{! return propertyVariableName;}

@synthesized (assign) mutator implementation

- (void)propertyName:(DataType)newPropertyValue{! propertyVariableName = newPropertyValue;}

@synthesized (retain) mutator implementation

- (void)propertyName:(DataType)newPropertyValue{! [propertyVariableName release];! propertyVariableName = [newPropertyValue retain];}

@synthesized (copy) mutator implementation

- (void)propertyName:(DataType)newPropertyValue{! if (propertyVariableName != newPropertyValue)! {! ! [propertyVariableName release];! ! propertyVariableName = [newPropertyValue copy];! }}

Objective-C, Foundation, Properties and Collections

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 01.5

Page 7: Ios Quick Ref

NSUserDefaults Methods

+resetStandardUserDefaults+standardUserDefaults // synch after chg-addSuiteNamed:-arrayForKey: // returns nil if no instances-boolForKey:-dataForKey:-dictionaryForKey:-dictionaryRepresentation-doubleForKey:-floatForKey:-init-integerForKey:-objectForKey:-persistentDomainForName:-persistentDomainNames-registerDefaults:-removeObjectForKey:-removePersistentDomainForName:-removeSuiteNamed:-removeVolatileDomainForName:-setBool:forKey:-setDouble:forKey:-setFloat:forKey:-setInteger:forKey:-setObject:forKey:-setPersistentDomain:forName:-setURL:forKey:-setVolatileDomain:forName:-stringArrayForKey:-stringForKey:-synchronize-URLForKey:-volatileDomainForName:-volatileDomainNames

Property List Constituent Data Types

NSArrayNSDictionaryNSNumberNSStringNSDateNSData

NSIndexPath Methods

+indexPathWithIndex:+indexPathWithIndexes:length:-indexAtPosition:-indexPathByAddingIndex:-indexPathByRemovingLastIndex-initWithIndex:-initWithIndexes:length:-length

NSUserDefaults Domain External NSString Constants (NSUserDefaults.h)

NSGlobalDomain NSRegistrationDomainNSArgumentDomain

Objective-C, Foundation, Properties and Collections

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 01.6

Page 8: Ios Quick Ref

Unit Test Macros

STFail(desc, ...)STAssertEqualObjects(object1, object2, desc, ...)STAssertEquals(value1, value2, desc, ...)STAssertEqualsWithAccuracy(value1, value2, desc, ...)STAssertNil(expression, desc, ...)STAssertNotNil(expression, desc, ...)STAssertTrue(expression, desc, ...)STAssertFalse(expression, desc, ...)STAssertThrows(expression, desc, ...)STAssertThrowsSpecifc(expression, exception_class, desc, ...)STAssertThrowsSpecificNamed(expr, exception_class, exception_name, desc, ...)STAssertNoThrow(expression, desc, ...)STAssertNoThrowSpecific(expression, exception_class, desc, ...)STAssertNoThrowSpecificNamed(expression, exception_class, exception_name, desc, ...)STAssertTrueNoThrow(expression desc, ...)STAssertFalseNoThrow(expression, desc, ...)

Unit Test Driver Header (.h) File Structure

#define USE_APPLICATION_UNIT_TEST 1

#import <SenTestingKit/SenTestingKit.h>#import <UIKit/UIKit.h>#import <CustomClass.h>

@interface CustomClassTest : SenTestCase

- (void)setUp;- (void)tearDown;- (void)testCustomClass;

@end

Unit Test Driver Implementation (.m) File Structure

#define USE_APPLICATION_UNIT_TEST 1

#import <CustomClassTest.h>

@implementation CustomClassTest

- (void)setUp{! ...}- (void)tearDown{! ...}- (void)testCustomClass{! ...}

@end

Unit Testing

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 02.1

Page 9: Ios Quick Ref

Common Core Graphics Types

CGFloat // for graphic coordinatesCGPoint // CGPointMake(x, y) CGFloat x CGFloat yCGSize // CGSizeMake(width, height) CGFloat width CGFloat heightCGRect // CGRectMake(x, y, width, height) CGPoint origin CGSize size

Common Core Graphics Functions

UIGraphicsGetCurrentContext();CGContextBeginPath(context);CGContextMoveToPoint(context, x, y);CGContextAddLineToPoint(context, x, y);CGContextClosePath(context);CGPath*(); // functions for reusing paths

UIColor Methods and Properties

+primaryColor+clearColor+colorWith*+lightTextColor-setFill:-setStroke:

UIImage Methods and Properties

+imageNamed:+imageWithContentsOfFile:+imageWithData:-drawAsPatternInRect:-drawAtPoint:-drawAtPoint:blendMode:alpha:-drawInRect:-drawInRect:blendMode:alpha:-initWithContentsOfFile:-initWithData:(ro) CGFloat scale(ro) CGSize sizeUIGraphicsGetImageFromCurrentContext();UIGraphicsEndImageContext();

UIImageView Methods and Properties

-initWithImage:-initWithImage:highlightedImage:-isAnimating-startAnimating-stopAnimatingNSTimeInterval animationDuration(copy) NSArray *animationImagesNSInteger animationRepeatCountBOOL highlighted(copy) NSArray *highlightedAnimationImages(retain) UIImage *highlightedImage(retain) UIImage *imageBOOL userInteractionEnabled = NO

Standard Views of Views

UIWebViewUIScrollView UITextView UITableViewUITableViewCell

Drawing Subroutine

- (void)drawGreenCircle:(CGContextRef)context{! UIGraphicsPushContext(context);! // Set color properties, etc.! // Draw...! UIGraphicsPopContext();}

UIImageOrientation Enumeration Constants (UIImage.h)

UIImageOrientationUpUIImageOrientationDown 180 degree rotationUIImageOrientationLeft 90 degrees counter-clockwiseUIImageOrientationRight 90 degrees clockwiseUIImageOrientationUpMirrored as above, but mirrored along other axis; horizontal flipUIImageOrientationDownMirrored horizontal flipUIImageOrientationLeftMirrored vertical flipUIImageOrientationRightMirrored vertical flip

Graphics, Drawing, and Images

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 03.1

Page 10: Ios Quick Ref

Standard Controllers of Controllers

UINavigationControllerUITabBarControllerUISplitViewController

UIScreen Methods and Properties

+screens+mainScreen(ro) CGRect applicationFrame // good view frame dflt(ro,retain) UIScreen *mirroredScreen(ro) CGFloat scale// A good view default frame is [[UIScreen mainScreen] applicationFrame];

UIApplicationDelegate Events

-applicationDidFinishLaunchingWithOptions:-applicationDidBecomeActive:-applicationWillResignActive:-applicationDidReceiveMemoryWarning:-applicationWillTerminate:-applicationSignificantTimeChange:-application:willChangeStatusBarOrientation:-application:didChangeStatusBarOrientation:-applicationDidEnterBackground:-applicationWillEnterForeground:

UIViewController Methods and Properties

-dismissModalViewControllerAnimated:-initWithNibName:bundle:-isEditing-isModalInPopover-presentModalViewController:animated:CGSize contentSizeForViewInPopoverBOOL editing(ro) UIInterfaceOrientation interfaceOrientationBOOL modalInPopover = NOUIModalPresentationStyle modalPresentationStyleUIModalTransitionStyle modalTransitionStyle = UIModalTransitionStyleCoverVertical(ro) UIViewController *modalViewController(ro) UINavigationController *navigationController(ro,retain) UINavigationItem *navigationItem(ro,retain) NSBundle *nibBundle(ro,copy) NSString *nibName(ro) UIViewController *parentViewController(ro,retain) UISearchDisplayController *searchDisplayController(ro,retain) UISplitViewController *splitViewController(ro,retain) UITabBarController *tabBarController(retain) UITabBarItem *tabBarItem(copy) NSString *title(retain) NSArray *toolbarItems(retain) UIView *viewBOOL wantsFullScreenLayout = NO

UIViewController Events

-loadView-viewDidLoad-viewWillDisappear:-viewDidDisappear:-viewWillAppear:-viewDidAppear:-shouldAutorotateToInterfaceOrientation:-didRotateFromInterfaceOrientation:

Physical Display Sizes

Unit Size in Pixels Pixels per Inch

iPod Touch 2nd Generation 480x320 163

iPod Touch 3rd Generation 480x320 163

iPod Touch 4th Generation 960x640 326

iPhone 3G 480x320 163

iPhone 3GS 480x320 163

iPhone 4 960x640 326

iPad 1024x768 132

iPad 2 1024x768 132

Detecting Device Environment from Universal Applications

• Conditionally make newer API calls using introspection, for example:respondsToSelector:@selector(contentScaleFactor)

• Or decide based on what controller of controllers you’re in, for example:if (self.splitViewController != nil) ...

• Or decide based on whether I’m already on-screen, e.g., when in split view vs. nav view:if (self.view.window) ...

• Or decide based on how big the current screen is (based on points, not pixels; only check thresholds), for example:CGRect screenBounds = [[UIScreen mainScreen] bounds];

• Or as a last resort, ask if I’m on an iPad, for example:if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ...if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ...

• Or conditionally load a .xib (not often done due to maintenance costs of 2 xibs), for example:(iPad ? @"MyNib-iPad" : @"MyNib")

4 Places View Controllers Can Be Initialized

• -initWithNibName:bundle:• -awakeFromNib• -viewDidLoad // Don’t initialize views or anything geometry-dependent (title ok)• -viewWillAppear:animated:

IBOutlet Memory Management Best Practices

• Make outlet properties private by declaring them in the implementation file; be sure to qualify the corresponding instance variable type declaration in the interface with IBOutlet as well.

• Don’t call outlet setters from dealloc in case setter performs complex operations just before object end-of-life.

Applications, Screens, Views, and ViewControllers

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 04.1

Page 11: Ios Quick Ref

UIView Methods and Properties

-addSubview:-bringSubviewToFront:-convertPoint:fromView:-convertPoint:toView:-convertRect:fromView:-convertRect:toView:-exchangeSubviewAtIndex:withSubviewAtIndex:-initWithFrame:-insertSubview:aboveSubview:-insertSubview:atIndex:-insertSubview:belowSubview:-isDescendantOfView:-pointInside:withEvent:-removeFromSuperview-sendSubviewToBack:-setNeedsDisplay-setNeedsDisplayInRect:-setNeedsLayout-sizeToFit-viewWithTag:CGFloat alpha(copy) CGFloat backgroundColorCGRect bounds; // internalCGPoint center; // superviewUIViewContentMode contentModeCGFloat contentScaleFactor // pixels per pointCGRect frame; // superviewBOOL hidden = NOBOOL opaque = YES // NO if alpha<1(ro,copy) NSArray *subviews(ro) UIView *superviewNSInteger tag = 0BOOL userInteractionEnabled = YES(ro) UIWindow *window

UIView Events

-didAddSubview:-didMoveToSuperview-didMoveToWindow-drawRect://override// IBOutlet properties automatically retained via setter// but must be released in dealloc (by release) &// viewDidUnload (by = nil)-willMoveToSuperview:-willMoveToWindow:-willRemoveSubview:

UINavigationController Methods and Properties

-init-initWithRootViewController:-pushViewController:animated:-popViewControllerAnimated:-setViewControllers:animated:<UINavigationControllerDelegate> delegate(ro) UINavigationBar *navigationBarBOOL navigationBarHidden = NO(ro) UIToolbar *toolbarBOOL toolbarHidden = YES(ro,retain) UIViewController *topViewController(copy) NSArray *viewControllers(ro,retain) UIViewController *visibleViewController

UIModalTransitionStyle Enumeration Constants (UIViewController.h)

UIModalTransitionStyleCoverVertical = 0 UIModalTransitionStyleCrossDissolveUIModalTransitionStyleFlipHorizontal UIModalTransitionStylePartialCurl

UIModalPresentationStyle Enumeration Constants (UIViewController.h)

UIModalPresentationFullScreen = 0 UIModalPresentationFormSheetUIModalPresentationPageSheet UIModalPresentationCurrentContext

UIView Core Properties

UIScreen

UIScreen.application-

Frame

Status Bar

UIView.bounds

UIView.frame

(superview'scoord. sys.)

UIView.center

(superview'scoord. sys.)

iPad 9:24 PM

(0,0)

UIViewContentMode Enumeration Constants (UIView.h)

UIViewContentModeScaleToFill UIViewContentModeLeftUIViewContentModeScaleAspectFit UIViewContentModeRightUIViewContentModeScaleAspectFill UIViewContentModeTopLeftUIViewContentModeRedraw UIViewContentModeTopRightUIViewContentModeCenter UIViewContentModeBottomLeftUIViewContentModeTop UIViewContentModeBottomRightUIViewContentModeBottom

Applications, Screens, Views, and ViewControllers

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 04.2

Page 12: Ios Quick Ref

UITabBarController Methods and Properties

-setViewControllers:animated:(copy) NSArray *customizableViewControllers<UITabBarControllerDelegate> delegate(ro) UINavigationController *moreNavigationControllerNSUInteger selectedIndexUIViewController *selectedViewController(ro) UITabBar *tabBar(copy) NSArray *viewControllers

UITabBarItem Methods and Properties

-initWithTabBarSystemItem:tag:-initWithTitle:image:tag:(copy) NSString *badgeValue;

UITabBarSystemItem Enumeration Constants (UITabBarItem.h)

UITabBarSystemItemMore UITabBarSystemItemHistoryUITabBarSystemItemFavorites UITabBarSystemItemBookmarksUITabBarSystemItemFeatured UITabBarSystemItemSearchUITabBarSystemItemTopRated UITabBarSystemItemDownloadsUITabBarSystemItemRecents UITabBarSystemItemMostRecentUITabBarSystemItemContacts UITabBarSystemItemMostViewed

Applications, Screens, Views, and ViewControllers

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 04.3

Page 13: Ios Quick Ref

UISplitViewController Properties

<UISplitViewControllerDelegate> delegate(copy) NSArray *viewControllers

UIPopoverController Methods and Properties

-dismissPopoverAnimated:-initWithContentViewController:-presentPopoverFromBarButtonItem: permittedArrowDirections:animated:-presentPopoverFromRect:inView: permittedArrowDirections:animated:-setContentViewController:animated:-setPopoverContentSize:animated:(retain) UIViewController *contentViewController<UIPopoverControllerDelegate> delegate(copy) NSArray *passthroughViews;(ro) UIPopoverArrowDirection popoverArrowDirectionCGSize popoverContentSize(ro) BOOL popoverVisible

UIPopoverDelegate Events

-popoverControllerShouldDismissPopover:-popoverControllerDidDismissPopover:

UISplitViewController Event Implementation

- (void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController:(UIPopoverController*)pc{! barButtonItem.title = aViewController.title;! self.navigationItem.rightBarButtonItem = barButtonItem;}- (void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)button{! self.navigationItem.rightBarButtonItem = nil;}- (void)splitViewController:(UISplitViewController *)svc popoverController:(UIPopoverController *)pc willPresentViewController:(UIViewController*)aViewController{! // Do nothing because we know nothing of the left view controller.! // This is the default implementation.}

UIPopoverArrowDirection Bitmask Constants (UIPopoverController.h)

UIPopoverArrowDirectionUpUIPopoverArrowDirectionDownUIPopoverArrowDirectionLeftUIPopoverArrowDirectionRightUIPopoverArrowDirectionAny = UIPopoverArrowDirectionUp | UIPopoverArrowDirectionDown | UIPopoverArrowDirectionLeft | UIPopoverArrowDirectionRightUIPopoverArrowDirectionUnknown = NSUIntegerMax

Applications, Screens, Views, and ViewControllers

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 04.4

Page 14: Ios Quick Ref

UIGestureRecognizer Methods and Properties

-addTarget:action:-initWithTarget:action:-locationInView:-locationOfTouch:inView:-removeTarget:action:-reset // override<UIGestureRecognizerDelegate> delegateBOOL enabled(ro) UIGestureRecognizerState state(ro) UIView *view

UITapGestureRecognizer Methods and Properties

NSUInteger numberOfTapsRequired = 1NSUInteger numberOfTouchesRequired = 1

UIPinchGestureRecognizer Methods & Properties

CGFloat scale(ro) CGFloat velocity

UIRotationGestureRecognizer MethodsProperties

CGFloat rotation(ro) CGFloat velocity

UISwipeGestureRecognizer Methods & Properties

UISwipeGestureRecognizerDirection directionNSUInteger numberOfTouchesRequired = 1

UIPanGestureRecognizer Methods & Properties

-setTranslation:inView:-translationInView:-velocityInView:NSUInteger maximumNumberOfTouchesNSUInteger minimumNumberOfTouches

UILongPressGestureRecognizer MethodsProperties

CGFloat allowableMovement = 10 // pixelsCFTimeInterval minimumPressDuration = 0.5 // secNSUInteger numberOfTapsRequired = 0NSInteger numberOfTouchesRequired = 1 // fingers

Gesture Recognizer Implementation

// Typically registered from a view controller- (void)viewDidLoad{ self.gv = [[GraphView alloc] init]; self.gv.backgroundColor = [UIColor whiteColor]; self.view = self.gv; UIGestureRecognizer *pangr = [[UIPanGestureRecognizer alloc]! initWithTarget:self.view action:@selector(pan:)]; [self.view addGestureRecognizer:pangr]; [pangr release];! ...}// Typically implemented in a view (could be anywhere,// though only views actually recognize gestures).- (void)pan:(UIPanGestureRecognizer *)gesture{ if (gesture.state == UIGestureRecognizerStateChanged ||! gesture.state == UIGestureRecognizerStateEnded) { CGPoint translation = [gesture translationInView:self]; self.origin = CGPointMake(self.origin.x + translation.x,! self.origin.y + translation.y); [gesture setTranslation:CGPointZero inView:self]; }}

UIGestureRecognizerState Enumeration Constants (UIGestureRecognizer.h)

UIGestureRecognizerStatePossibleUIGestureRecognizerStateBeganUIGestureRecognizerStateChangedUIGestureRecognizerStateEndedUIGestureRecognizerStateCancelledUIGestureRecognizerStateFailedUIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded

UISwipeGestureRecognizerDirection Bitmask Constants (UISwipeGestureRecognizer.h)

UISwipeGestureRecognizerDirectionRight UISwipeGestureRecognizerDirectionUpUISwipeGestureRecognizerDirectionLeft UISwipeGestureRecognizerDirectionDown

Gestures

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 05.1

Page 15: Ios Quick Ref

UIWebView Methods and Properties

-goBack-goForward-loadData:MIMEType:textEncodingName:baseURL:-loadHTMLString:baseURL:-loadRequest:-reload-stopLoading-stringByEvaluatingJavaScriptFromString:BOOL allowsInlineMediaPlayback(ro) BOOL canGoBack(ro) BOOL canGoForwardUIDataDetectorTypes dataDetectorTypes<UIWebViewDelegate> delegate(ro) BOOL loadingBOOL mediaPlaybackRequiresUserAction(ro,retain) NSURLRequest *requestBOOL scalesPagesToFit = NO

UIWebView Events

webView:didFailLoadWithError:webView:shouldStartLoadWithRequest: navigationType:webViewDidFinishLoad:webViewDidStartLoad:

NSURL Methods and Properties

+fileURLWithPath:+fileURLWithPath:isDirectory:+fileURLWithPathComponents:+URLWithString:+URLWithString:relativeToURL:-absoluteString-absoluteURL-baseURL-fragment-host-initFileURLWithPath:-initFileURLWithPath:isDirectory:-initWithScheme:host:path:-initWithString:-initWithString:relativeToURL:-isEqual:-isFileURL-lastPathComponent-parameterString-password-path-pathComponents-pathExtension-port-query-relativePath-relativeString-resourceSpecifier-scheme-standardizedURL-URLByAppendingPathComponent:-URLByAppendingPathExtension:-URLByDeletingLastPathComponent-URLByDeletingPathExtension-URLByResolvingSymlinksInPath-URLByStandardizingPath-user

UIWebViewNavigationType Enumeration Constants (UIWebView.h)

UIWebViewNavigationTypeLinkClickedUIWebViewNavigationTypeFormSubmittedUIWebViewNavigationTypeBackForwardUIWebViewNavigationTypeReloadUIWebViewNavigationTypeFormResubmittedUIWebViewNavigationTypeOther

UIDataDetectorTypes Bitmask Constants (UIDataDetectors.h)

UIDataDetectorTypePhoneNumberUIDataDetectorTypeLinkUIDataDetectorTypeAddressUIDataDetectorTypeCalendarEventUIDataDetectorTypeNone = 0UIDataDetectorTypeAll = NSUIntegerMax

NSURLRequestCachePolicy Enumeration Constants (NSURLRequest.h)

NSURLRequestUseProtocolCachePolicy = 0NSURLRequestReloadIgnoringLocalCacheDataNSURLRequestReloadIgnoringLocalAndRemoteCacheDataNSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheDataNSURLRequestReturnCacheDataElseLoadNSURLRequestReturnCacheDataDontLoadNSURLRequestReloadRevalidatingCacheData

NSURLRequestNetworkServiceType Enumeration Constants (NSURLRequest.h)

NSURLNetworkServiceTypeDefault NSURLNetworkServiceTypeVoIP

URLs and WebViews

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 06.1

Page 16: Ios Quick Ref

NSURLRequest Methods and Properties

+requestWithURL:+requestWithURL:cachePolicy:timeoutInterval:-allHTTPHeaderFields-cachePolicy-HTTPBody-HTTPBodyStream-HTTPMethod-initWithURL:-initWithURL:cachePolicy:timeoutInterval:-mainDocumentURL-networkServiceType-timeoutInterval-URL-valueForHTTPHeaderField:

URLs and WebViews

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 06.2

Page 17: Ios Quick Ref

UIScrollView Methods and Properties

-flashScrollIndicators // use when view is revealed...-scrollRectToVisible:animated:-setContentOffset:animated:-setZoomScale:animated:-zoomToRect:animated:BOOL alwaysBounceHorizontal = NOBOOL alwaysBounceVertical = NOBOOL bounces = YESBOOL bouncesZoom = YESUIEdgeInsets contentInset = UIEdgeInsetsZeroCGPoint contentOffset = CGPointZeroCGSize contentSize = CGSizeZero(ro) BOOL deceleratingfloat decelerationRate<UIScrollViewDelegate> delegateBOOL directionalLockEnabled = NO(ro) BOOL draggingUIScrollViewIndicatorStyle indicatorStyle = UIScrollViewIndicatorStyleDefaultfloat maximumZoomScale // zooming won’t workfloat minimumZoomScale // unless both are setBOOL pagingEnabled = NOBOOL scrollEnabled = YESUIEdgeInsets scrollIndicatorInsets = UIEdgeInsetsZero(ro) BOOL tracking(ro) BOOL zoomBouncing(ro) BOOL zoomingfloat zoomScale = 1.0

UIScrollViewDelegate Events

-scrollViewDidEndScrollingAnimation:-scrollViewDidEndZooming:withView:atScale:-scrollViewDidScroll:-scrollViewDidScrollToTop:-scrollViewDidZoom:-scrollViewWillBeginZooming:withView:-viewForZoomingInScrollView:

UITextView Methods and Properties

-hasText-scrollRangeToVisible:UIDataDetectorTypes dataDetectorTypes<UITextViewDelegate> delegateBOOL editable = YES(retain) UIFont *font(retain) UIView *inputAccessoryView(retain) UIView *inputViewNSRange selectedRange(copy) NSString *textUITextAlignment textAlignment(retain) UIColor *textColor

ScrollIndicatorStyle Enumeration Constants (UIScrollView.h)

UIScrollViewIndicatorStyleDefault UIScrollViewIndicatorStyleWhiteUIScrollViewIndicatorStyleBlack

Scroll Deceleration External float Constants (UIScrollView.h)

UIScrollViewDecelerationRateNormal UIScrollViewDecelerationRateFast

ScrollViews, TextViews, and TableViews

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 07.1

Page 18: Ios Quick Ref

UITableView Methods and Properties

-beginUpdates-cellForRowAtIndexPath:-deleteRowsAtIndexPaths:withRowAnimation:-deleteSections:withRowAnimation:-dequeueReusableCellWithIdentifier:-deselectRowAtIndexPath:animated:-endUpdates-indexPathForCell:-indexPathForRowAtPoint:-indexPathForSelectedRow-indexPathsForRowsInRect:-indexPathsForVisibleRows-initWithFrame:style:-insertRowsAtIndexPaths:withRowAnimation:-insertSections:withRowAnimation:-numberOfRowsInSection:-numberOfSections-rectForFooterInSection:-rectForHeaderInSection:-rectForRowAtIndexPath:-rectForSection:-reloadData-reloadRowsAtIndexPaths:withRowAnimation:-reloadSectionIndexTitles-reloadSections:withRowAnimation:-scrollToNearestSelectedRowAtScrollPosition: animated:-scrollToRowAtIndexPath:atScrollPosition:animated:-selectRowAtIndexPath:animated:scrollPosition:-setEditing:animated:-visibleCellsBOOL allowsSelection = YESBOOL allowsSelectionDuringEditing = NO(retain) UIView *backgroundView<UITableViewDataSource> dataSource<UITableViewDelegate> delegateBOOL editingCGFloat rowHeightCGFloat sectionFooterHeightCGFloat sectionHeaderHeightNSInteger sectionIndexMinimumDisplayRowCount = NSIntegerMax(retain) UIColor *separatorColor = grayColorUITaleViewCellSeparatorStyle separatorStyle(ro) UITableViewStyle style(retain) UIView *tableFooterView(retain) UIView *tableHeaderView

UITableViewDelegate Events

-tableView: accessoryButtonTappedForRowWithIndexPath:-tableView:didDeselectRowAtIndexPath:-tableView:didEndEditingRowAtIndexPath:-tableView:didSelectRowAtIndexPath:-tableView:editingStyleForRowAtIndexPath:-tableView:indentationLevelForRowAtIndexPath:-tableView:shouldIndentWhileEditingRowAtIndexPath:-tableView: targetIndexPathForMoveFromRowAtIndexPath: toProposedIndexPath:-tableView:viewForFooterInSection:-tableView:viewForHeaderInSection:-tableView:willBeginEditingRowAtIndexPath:-tableView:willDeselectRowAtIndexPath:-tableView:willDisplayCell:forRowAtIndexPath:-tableView:willSelectRowAtIndexPath:

Table View Style Enumeration Constants (UITableView.h)

UITableViewStylePlain UITableViewStyleGrouped

Table View Scroll Position Enumeration Constants (UITableView.h)

UITableViewScrollPositionNone UITableViewScrollPositionMiddleUITableViewScrollPositionTop UITableViewScrollPositionBottom

Table Cell Insertion and Deletion Animation Enumeration Constants (UITableView.h)

UITableViewRowAnimationFade UITableViewRowAnimationTop UITableViewRowAnimationRight UITableViewRowAnimationBottomUITableViewRowAnimationLeft UITableViewRowAnimationMiddle UITableViewRowAnimationNone

Section Index NSString Icon Constants (UITableView.h)

UITableViewIndexSearch

ScrollViews, TextViews, and TableViews

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 07.2

Page 19: Ios Quick Ref

UITableViewDataSource Events

-numberOfSectionsInTableView:-sectionIndexTitlesForTableView:-tableView:canEditRowAtIndexPath:-tableView:canMoveRowAtIndexPath:-tableView:cellForRowAtIndexPath:-tableView:commitEditingStyle:forRowAtIndexPath:-tableView:moveRowAtIndexPath:toIndexPath:-tableView:numberOfRowsInSection:-tableView:sectionForSectionIndexTitle:atIndex:-tableView:titleForFooterInSection:-tableView:titleForHeaderInSection:

UITableViewCell Methods and Properties

-initWithStyle:reuseIdentifier:-prepareForReuse-setEditing:animated:-setHighlighted:animated:-setSelected:animated:UITableViewCellAccessoryType accessoryType = UITableViewCellAccessoryNone(retain) UIView *accessoryView(retain) UIView *backgroundView(ro,retain) UIView *contentView(ro,retain) UILabel *detailTextLabelBOOL editingUITableViewCellAccessoryType editingAccessoryType(retain) UIView *editingAccessoryView(ro) UITableViewCellEditingStyle editingStyleBOOL highlighted = NO(ro,retain) UIImageView *imageViewNSInteger indentationLevelCGFloat indentationWidth = 10.0 // points(ro,copy) NSString *reuseIdentifierBOOL selected(retain) UIView *selectedBackgroundViewUITableViewCellSelectionStyle selectionStyleBOOL shouldIndentWhileEditing(ro) BOOL showingDeleteConfirmationBOOL showsReorderControl(ro,retain) UILabel *textLabel

UITableViewCell Events

-didTransitionToState:-willTransitionToState:

UITableViewController Methods and Properties

-initWithStyle:BOOL clearsSelectionOnViewWillAppear(retain) UITableView *tableView

Cell Style Enumeration Constants (UITableViewCell.h)

UITableViewCellStyleDefault UITableViewCellStyleValue1UITableViewCellStyleSubtitle UITableViewCellStyleValue2

Cell Selection Style Enumeration Constants (UITableViewCell.h)

UITableViewCellSelectionStyleNone UITableViewCellSelectionStyleBlue UITableViewCellSelectionStyleGray

Cell Editing Style Enumeration Constants (UITableViewCell.h)

UITableViewCellEditingStyleNone UITableViewCellEditingStyleDelete UITableViewCellEditingStyleInsert

Cell Accessory Type Enumeration Constants (UITableViewCell.h)

UITableViewCellAccessoryNoneUITableViewCellAccessoryDisclosureIndicatorUITableViewCellAccessoryDetailDisclosureButtonUITableViewCellAccessoryCheckmark

Cell State Mask Bitmask Constants (UITableViewCell.h)

UITableViewCellStateDefaultMask = 0UITableViewCellStateShowingEditControlMaskUITableViewCellStateShowingDeleteConfirmationMask

Cell Separator Style Enumeration Constants (UITableViewCell.h)

UITableViewCellSeparatorStyleNoneUITableViewCellSeparatorStyleSingleLineUITableViewCellSeparatorStyleSingleLineEtched

ScrollViews, TextViews, and TableViews

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 07.3

Page 20: Ios Quick Ref

Table View Cell Convenience Definitions (UITableViewCell.h)

UITableViewCellSeparatorStyleDoubleLineEtched =UITableViewCellSeparatorStyleSingleLineEtchedUITableViewCellStateEditingMask =UITableViewCellStateShowingEditControlMask

ScrollViews, TextViews, and TableViews

Objective-C & iOS SDK Quick Reference 2011.09.09! Copyright © 2011 ASAP WebSoft, LLC! http://www.asapwebsoft.com/iosquickref 07.4