The ios System
System Overview
System Overview
System Overview
System Overview
System Overview
System Overview
Foundation Classes (Useful)
Foundation Framework Value and collection classes User defaults Archiving Notifications Undo manager Tasks, timers, threads File System, pipes, I/O, bundles
NSObject Root class Introspection Object equality Implements many basics Memory management
NSString General-purpose Unicode string support Unicode coding system Conssitently used throughout Cocoa Touch instead of char / char * Easy to suuport any language
String Constants In C: simple In ObjC @ just as simple Constant string are NSString instances: NSString *string = @ hello 41308
stringwithformat & format String Similar to printf or sprintf with %@ added for objects: NSString astring = @ Dada NSString *log = [ NSString stringwithformat:@ lan mo %@, astring]; Similar to printf or sprintf with %@ added for objects: NSLog(@ lan mo %@ astring);
Other Common NSString methods - (BOOL) isequaltostring:(nsstring*) string; - (BOOL) hasprefix: (NSString*) string; - (int) intvalue; - (double) doublevalue;
NSMutableString NSMutableString - subclasses of NSString Modifiable String +(id) string; -(void)appendstring:(nsstring *)string; -(void)appendformat:(nsstring*)format,...;
Collections Array - ordered collection of objects Common enumeration mechanism Immutable and mutable versions Prevents unexpected changes Dictionary - collection of key-value paris Set - unordered collection of unique objects Immutable collections - share without error Mutable objects carry performance overhead
Common NSArray methods NSArray +arraywithobjects:(id)firstobj,..., nil; -(unsigned)count; -(id)objectatindex:(unsigned)index; -(unsigned)indexofobject:(id)object; NSArray * array = [NSArray arraywithobjects:@ A, B, C, nil); if([array indexofobject:@ D ] == NSNotFound) { NSLog(@ Not Found ); }
NSMutableArray NSMutableArray - subclasses of NSArray Can insert, remove object in an Array +(NSMutableArray *)array; -(void)addobject:(id)object; -(void)removeobject:(id)object; -(void)removeallobjects; -(void)insertobject:(id)object atindex:(unsigned)index;
NSDictionary Common NSDictionary methods + dictionarywithobjecsandkeys: (id)firstobject,...; - (unsigned)count; - (id)objectforkey:(id)key; Return nil if no object found
NSMutableDictionary NSMutableDictionary - subclasses of NSDictionary Can insert, remove object in a NSDictionary +(NSMutableDictionary *)dictionary; -(void)setobject:(id)object forkey:(id)key; -(void)removeobjectforkey:(id)key; -(void)removeallobjects;
Enumeration Consistent way of enumeration over objects in collections. Use with NSArray, Dictionary, NSSet, etc. //old Person *person; int count = [array count]; for(int i =0; i<count; i++) { NSLog([person description]); } //enumeration!!!! for(person *person in array) { NSLog([person description]); }
NSNumber In objc, you can use standard C primitive number NSNumber is used to wrap C number types as object. Subclass of NSValue Number for Collection (Array, Dict...) Common NSNumber methods: +(NSNumber*)numberWithInt:(ind)value; +(NSNumber*)numberWithDouble:(double)value (int) intvalue; (double)doublevalue;
View
View Fundamentals Rectangular area on screen Draw content Handles events (e.g. Touch ) Subclass of UIResponder (event handing class) Views arranged hierarchically every view has one superivew very view has zero or more subviews
UIWindow Views live inside of a window UIWindow is actually jst a view adds some additional functionality specific to top level One UIWindow for an iphone app Contains the entire view hierarchy Set up by default in Xcode template project
View - Manipulation Add /remove views in IB or using UIView methods -(void)addsubview:(uiview *)view; -(void)removefromsuperview; Manipulate the view hierarchy manually: -(void) insertsubview:atindex: -(void) insertsubview:belowsubview: -(void)insertsubview:abovesubview: -(void)exchangesubviewatindex:withsubviewatindex
View-related structures CGPoint location in space: {x, y} CGSize dimension: {width, height} CGRect location and dimension: {origin, size}
View-related structures
View-related structures
Creating view - by IB View is created commonly by Interface Builder Drag out any of existing view objects (button, label and etc) Or drag generic UIView and set customclass
Manual Creation View are initialized using -initwithframe: CGRect frame = CGRectMake(0,0,200,150); UIView *v = [[UIView alloc] initwithframe:frame]; //add subview into window [window addsubview:label];
Defining Custom Views Subclass UIView For custom drawing, you override: -(void)drawrect:(cgrect)rect; For event handling, you override: -(void)touchesbegan:(nsset*)touches withevent:(uievent *)event; -(void)touchesmoved:(nsset*)touches withevent:(uievent *)event; -(void)touchesended:(nsset*)touches withevent:(uievent *)event; -(void)touchescancelled:(nsset*)touches withevent:(uievent *)event;
Try - MoveMe
Animation
UIView Animations UIView supports a number of animatable properties frame, bounds, center, alpha, transform Create blocks around changes to animatable properties Animations run asynchronously and automatically Additional animation options: delay before start start at specific time curve (easing) repeat count autoreverses (e.g. ping pong)
View Animation Example -(void)showadvancedoptions{ //assume polygon view and options view [UIView beginanimations: @ advancedanimations context:nil]; [UIView setanimationduration:0.3]; //make optionsview visible (alpha is currently 0.0) optionsview.alpha = 1.0; //move the polygonview down CGRect polygonframe = polygonview.frame; polygonframe.origin.y += 200; polygonview.frame = polygonframe; } [UIView commitanimations];
UIView animation allow for a delegate -(void)showadvancedoptions{ //assume polygon view and options view [UIView beginanimations: @ advancedanimations context:nil]; [UIView setanimationduration:0.3]; //make optionsview visible (alpha is currently 0.0) optionsview.alpha = 1.0; //move the polygonview down CGRect polygonframe = polygonview.frame; polygonframe.origin.y += 200; polygonview.frame = polygonframe; } [UIView commitanimations];
Drawing Views
-(void)drawrect:(cgrect)rect [UIView drawrect:] does nothing by default If not overridden, the background Color is used to fill Override - drawrect: to draw a custome view rect argument is area to draw drawrect: is invoked automatically When a view needs to be redrawn use: - (void)setneedsdisplay;
CoreGraphics and Quartz 2D UIKit offers basic drawing functions UIRectFill(CGRect rect) & UIRectFrame(CGRect rect) CoreGraphics: Drawing APIs CG is a C-based API (not Objective-C!!!) which offers simple but powerful graphics primitives Graphics context Transformations Paths Colors Fonts and Painting operations
Graphics Contexts All drawing is done into an opaque graphics context Draws to screen, bitmap buffer, printer, PDF, etc Graphics context setup automatically before invoking drawrect defines current path, line width, transform, etc. Access the graphics context within drawrect: Calling (CGContextRef)UIGraphicsGetCurrentContext(void); Use CG calls to change settings Context only valid for current call to drawrect
CG Wrapper Some CG functionality wrapped by UIKit UIColor Convenience for common colors: UIColor *redcolor = [UIColor redcolor]; UIFont Access system font: UIFont *font = [UIFont systemfontsize:14.0];
Simple drawrect: example Draw a solid color and shape -(void)drawrect:(cgrect)rect{ CGRect bounds = [self bounds]; [[UIColor graycolor] set]; UIRectFill(bounds); CGRect sq = CGRectMake(10,10,50,100); [[UIColor redcolor] set]; UIRectFill(sq); } [[UIColor blackcolor] set]; UIRectFrame(sq);
Draw more complex shapes Common steps for drawrect: are Get current graphics context Define a path Set a color Stroke or fill path Repeat, if necessary
Paths & CGPath CoreGraphics paths define shapes Made up of lines, arcs curves and rectangles Creation and drawing of paths are two distinct operation Define path first, then draw it Two parallel sets of functions for using paths
Simple Path Example - (void) draw Rect:(CGRect)rect{ CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor graycolor set]; UIRectFill([self bounds]); CGContextBeginPath(context); CGContextMoveToPoint(context, 75, 10); CGContextAddLineToPoint(context, 10, 150); CGContextAddLineToPoint(context, 160, 150); CGContextClosePath(context); } [[UIColor redcolor] setfill]; [[UIColor blackcolor] setstroke]; CGContextDrawPath(context, kcgpathfillstroke);