Download presentation
Presentation is loading. Please wait.
Published byJordan Ferguson Modified over 9 years ago
1
Toward iOS programming
2
Overview Objective-C is an object oriented language. follows ANSI C style coding with methods from Smalltalk Flexible almost everything is done at runtime. Dynamic Binding Dynamic Typing Dynamic Linking
3
Inventors Objective-C was invented by two men, Brad Cox and Tom Love. Both were introduced to Smalltalk at ITT in 1981 Cox thought something like Smalltalk would be very useful to application developers Cox modified a C compiler and by 1983 he had a working Object-oriented extension to C called OOPC.
4
Development Tom Love acquired a commercial copy of Smalltalk-80 while working for Schlumberger Research With direct access Smalltalk, Love added more to OOPC making the final product, Objective-C. In 1986 they release Objective-C through their company “Stepstone”
5
NeXT and NeXTSTEP In 1988 Steve Jobs acquires Objective- C license for NeXT Used Objective-C to build the NeXTSTEP Operating System Objective-C made interface design for NeXTSTEP much easier NeXTSTEP was derived from BSD Unix In 1995 NeXT gets full rights to Objective-C from Stepstone
6
OPENSTEP API Developed in 1993 by NeXT and Sun An effort to make NeXTSTEP-like Objective-C implementation available to other platforms. In order to be OS independent Removed dependency on Mach Kernel Made low-level data into classes Paved the way for Mac OS X, GNUstep
7
Apple and Mac OS X NeXT is taken over by Apple in 1996 and put Steve Jobs and his Objective-C libraries to work Redesigned Mac OS to use objective-C similar to that of NeXTSTEP Developed a collection of libraries named “Cocoa” to aid GUI development Release Mac OS X (ten), which was radically different than OS 9, in March 2001
8
The Cocoa API Developed by Apple from NeXTSTEP and OPENSTEP Has a set of predefined classes and types such as NSnumber, NSstring, Nsdate, etc. NS stands for NeXT-sun Includes a root class NSObject where words like alloc, retain, and release come from
9
Dynamic Language Almost everything is done at runtime Uses dynamic typing, linking, and binding This allows for greater flexibility Minimizes RAM and CPU usage
10
To Import or Include? C/C++’s #include will insert head.h into the code even if its been added before. Obj-C’s #import checks if head.h has been imported beforehand. #import “ head.h”
11
Objective-C Is a SUPERSET of C
13
Primitive data types from C int, short, long float,double char
14
Operators same as C + - * / ++ --
15
Address and Pointers Same as C To get address of a variable i &i Pointer int *addressofi = &I;
17
Conditionals and Loops Same as C/C++ if / else if/ else for while break ontinue do-while for(int i=0; i< 22; i++) { printf(“Checking i=“@d\n”, i); if(i+90 == i*i) { break;} }
18
for in loop Introduced in Objective-C 2.0 (“fast enumeration”) for(Item_Type *item in Collection_of_Items) { //do whatever with the item Nslog(@” Looking now at %@”, item); } Note: %@ in the NSLog converts whatever is passed (in this case item) to a string
19
Functions Same as C/C++ return_type functionName(type v1, type v2, ….) { //code of function } Example void showMeInfo(int age) { printf(“You are %d years old”, age); //or use NSLog() }
20
Global and static variables Same as C/C++ Global variables defined at top of file For static variables use keyword static before it static in CurrentYear = 2013;
21
Functions --- pass by reference Same as C/C++ return_type functionName(type v1, type *v2, ….) { //code of function } Example – call above int v1 = 2; int v2 = 3; functionName(v1, &v2);
22
Main Funciton –like C++ #import int main(int argc, const char *argv[]) { @autoreleasepool { //your code here******* //you can have C code if you wish or Objective-C return 0; } NOTE: Latest version of Objective-C uses Automatic Reference Counting (kind of like automatic garbage collection) ----to handle getting rid of not needed items in memory (avoiding memory leaks). YEAH! AUTOMATIC! -----like Java this way @autoreleasepool in a needed annotation around your main block of code to “enable” this
23
IMPORTANT --- we are doing iOS applications NOT mac OS applications We will be doing iOS application that have a different framework called Model View Controller ---- But, for some examples to learn concepts of Objective-C we will show some basic main.m files with main functions that are not iOS programs!!! We will learn iOS soon!
24
Main Function –like C++ #import int main(int argc, const char *argv[]) { @autoreleasepool { //takes care of “automatic release of not needed items //static method date with no parameters is invoked on NSDate class NSDate *now = [NSDate date]; //this will generate a new instance of NSDate with current time NSLog(@”The new date lives at %p”, now); //Objective-C function that is like printf to console double seconds = [now timeIntervalSince1970] //call timesInterrval* method on now object NSLog(@”It has been %f seconds since 1970”, seconds); NSDate *later = [now dateByAddingTimeInterval:100000]; //pass 100000 parameter to method NSLog(@”In 100,000 seconds will be %@”, later); //%@ means print as string return 0; }
26
Non-GUI – text output Two standard functions you see used printf() – same as C ○ printf(“Hi Lynne”); //this is actual C code NSLog() ○ NSLog(@”Hi Lynne”); //this is strictly Objective-C
28
Classes Have both definition file and implementation file : classname.h and classname.m Similar to how have.h and.cpp in C++
29
Declaring a class in ClassName.h #import @interface ClassName : Parent { //class variables int age; NSString name; } // methods declared -(void)setAge:(int)number; -(void)setName:(NSString)n; -(int)getAge; -(NSString)getName; @end #import #import “local-your-otherfiles.h” @interface ClassName: Parent { //class variables } //methods -(return_type) methodName:(type)param1, (type) param2; @end
30
Declaring methods C++ syntax Objective-C syntax void function(int x, int y, char z); Object.function(x, y, z); -(void) method:(int)x, (int)y, (char)z; [Object function:x, y, z]; - (return type) function_name: (type) p1, (type) p2, ***; Apply function to Object passing parameters x,y,z
31
Whats this + and – stuff? When declaring or implementing functions for a class, they must begin with a + or - + indicates a “class method” that can only be used by the class itself. (they are like static methods in Java invoked on class itself) - indicates “instance methods” to be used by the client program (public functions) –invoked on an object / class instance. (they are like regular methods in Java invoked on object)
32
Class Implementation File (ClassName.m) #import “ClassName.h” @implementation ClassName -(void)setAge:(int)number { age = number; } -(void)setName:(NSString)n { name = n; } -(int)getAge { return age; } -(NSString)getName { return name; } @end Remember our ClassName.h #import @interface ClassName : Parent { //class variables int age; NSString name; } // methods declared -(void)setAge:(int)number; -(void)setName:(NSString)n; -(int)getAge; -(NSString)getName; @end
33
An example….the class Node
34
Class Declaration (Interface) #import @interface Node : NSObject { Node *link; int contents; } +(id)new; -(void)setContent:(int)number; -(void)setLink:(Node*)next; -(int)getContent; -(Node*)getLink; @end Node.h Class is Node who’s parent is NSObject { class variables } +/- private/public methods of Class Class variables are private
35
Class Definition (Implementation) #import “Node.h” @implementation Node +(id)new { return [Node alloc];} -(void)setContent:(int)number {contents = number;} -(void)setLink:(Node*)next { [link autorelease]; link = [next retain]; } -(int)getContent {return contents;} -(Node*)getLink {return link;} @end Node.m Like your C++.cpp file >>just give the methods here
37
Creating class instances ClassName *object = [[ClassName alloc] init]; ClassName *object = [[ClassName alloc] initWith* ]; NSString* myString = [[NSString alloc] init]; Nested method call. The first is the alloc method called on NSString itself. This is a relatively low-level call which reserves memory and instantiates an object. The second is a call to init on the new object. The init implementation usually does basic setup, such as creating instance variables. The details of that are unknown to you as a client of the class. In some cases, you may use a different version of init which takes input: ClassName *object = [ClassName method_to_create]; NSString* myString = [NSString string]; Some classes may define a special method that will in essence call alloc followed by some kind of init Creating an Object
38
Object ---invoking a method, the basics Objective-C uses a Message Approach
39
Messages ---really weird (new) syntax Almost every object manipulation is done by sending objects a message Two words within a set of brackets, the object identifier and the message to send. Like C++ or Java’s Identifier.message() [Identifier message ]
40
Setting values for class variables of an object ---- THROUGH methods [object methodName]; [object setXXXMethod:value1]; [object setYYYYMethod:value2];
41
C++VS. Objective-C Adds OOP, metaprogramming and generic programming to C Comes with a std library Has numerous uses Large and complex code for OOP Only adds OOP to C Has no standard library; is dependant on other libraries Mostly used for application building Simpler way of handling classes and objects
42
Keyword: id The word ‘id’ indicates an identifier for an object much like a pointer in c++ This uses dynamic typing For example, if Pen is a class… extern id Pen; id myPen; myPen = [Pen new ]; id work like pointers to objects.
43
Memory Allocation Objects are created dynamically through the keyword, “alloc” Objects are automatically deallocated in latest Objective-C through automatic reference counting
44
Automatic Reference Counting Objective C uses ‘AUTOMATIC reference counting' as memory management keeps an internal count of how many times an Object is 'needed'. System makes sure that objects that are needed are not deleted, and when an object is not needed it is deleted.
45
iOS programs and @autoreleasepool You will notice (later when you learn) your iOS applications are setup in Xcode (the IDE) with @autoreleasepool setup This insures automatic release of unneeded items will take place for you.
47
linkList class #import "linkList.h" @implementation linkList +(id)new {return [linkList alloc];} -(void)insert:(int)value { id temp = [Node new]; [temp setContent:value]; [temp setLink:head]; head = [temp retain]; [temp release]; } -(void)append:(int)value { id last = [head getLink]; while ([last getLink] != nil) {last = [last getLink];} id temp = [Node new]; [temp setContent:value]; [last setLink:temp]; [temp release]; } -(void)remove { id temp = head; head = [head getLink]; [temp release]; } -(int)getValue { return [head getContent];} @end linkList.m Class linkList is child of previous Node class (not showing.h file for brevity)
48
Stack class (child of linkList) #import "linkList.h” @interface Stack : linkList {} +(id)new; -(void)push:(int)value; -(int)pop; @end #import "stack.h” @implementation Stack +(id)new {return [Stack alloc];} -(void)push:(int)value {[self insert:value];} -(int)pop { int ret = [self getValue]; //getValue method of parent linkList [self remove]; //remove method of parent linkList return ret; } @end stack.h stack.m self is like the C++/Java word this. Remember alloc creates the object in memory
49
Example: main.m #import "stack.h” int main(){ Stack *s = [Stack new]; [s push:1]; [s push:2]; printf("%d\t", [s pop]); [s push:3]; printf("%d\t", [s pop]); [s release]; return 0; } Run the program : 2 3 1 new is method defined in Stack class that simply that calls [Stack alloc] --- done for convinience Note only need to import “stack.h” because stack imports LinkList.h which imports Node.h which imports cocoa.h release is method to release this object s explicitly from memory
51
Primitive data types int, short, long float,double char BOOL = means boolean
52
NSInteger and NSUnteger NSInteger number; (Like long in C) NSUItneger another; (Like unsigned long in C) Objective-C data types that are 32-Bits on 32- Bit platforms and 64-bits on 64-bit platforms
53
NSString NSString *theMessage = @”hello world”; Number of characters in a string ○ NSUInteger charCount = [theMessage length]; Test if 2 strings equal ○ if([string_var_1 isEqual: string_var_2]) { //code for equal case }
54
String literal in Objective-C Begins with the @ symbol @”Lynne Grewe”; Some Examples NSString *myString = @”Hello World”; int len = [myString length]; OR int len = [@”Hello World” length]; OR NSString *myString = [[NSString alloc] initWithString:@”Hello World”]; int len = [myString length]; This is like “Lynne Grewe” in most other languages
55
Formatting Strings in output NSLog int a = 1; float b = 33.22; char c = ‘A’; NSLog(@”Integer %d Float: %f Char: %c”, a, b, c);
56
NSString ---not changeable International (any language) strings using Unicode. Compiler will create an NSString for you using @“foo” notation. An NSString instance can not be modified! They are immutable. Usual usage pattern is to send a message to an NSString and it will return you a new one. self.display.text = [self.display.text stringByAppendingString:digit]; self.display.text = [NSString stringWithFormat:@“%g”, brain.operand]; // class method Tons of utility functions available (case conversion, URLs, substrings, type conversions, etc.). Used throughout iOS instead of C language’s char * type.
57
NSMutableString ---changeable Mutable version of NSString. Somewhat rarely used. Can do some of the things NSString can do without creating a new one (i.e. in-place changes). NSMutableString *ms = [[NSMutableString alloc] initWithString:@“0.”]; NSMutableString *ms = [NSMutableString stringWithString:@“0.”]; // inherited from NSString [ms appendString:digit];
58
NSNumber Object wrapper around primitive types like int, float, double, BOOL, etc. NSNumber *num = [NSNumber numberWithInt:36]; float f = [num floatValue]; // would return 36 as a float (i.e. will convert types) Useful when you want to put multiple numeric primitive types in a collection (e.g. NSArray or NSDictionary).
59
NSValue Generic object wrapper for other non- object data types. CGPoint point = CGPointMake(25.0, 15.0); // CGPoint is a C struct NSValue *pointObject = [NSValue valueWithCGPoint:point];
60
NSData “Bag of bits.” Used to save/restore/transmit data throughout the iOS SDK.
61
NSDate “Used to find out the time right now or to store past or future times/dates. See also NSCalendar, NSDateFormatter, NSDateComponents.
62
NSArray – holds fixed array of points to objects NSArray *thearray = [NSArray arrayWithObjects:o1,o2,o3,o4, nil]; //get element [thearray objectAtIndex:0]; //element at index 0 Example NSDate *now = [NSDate date]; NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day //array of Dates NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday]; //get elements in array NSDate *first = [dateList objectAtIndex:0]; Methods are: count = gets number of items in array objectAtIndex:i = returns element i of array (starting from 0) Note: you can not add or remove a pointer from an NSArray ---fixed once created
63
NSArray – cycle through with for loop NSDate *now = [NSDate date]; NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day //array of Dates NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday]; //get elements in array NSDate *first = [dateList objectAtIndex:0]; NSUInteger dateCount = [dateList count]; for(int i=0; i<dateCount; i++) { NSDAte *d = [dateList objectAtIndex:i]; NSLog(@” Date is %@”, d); } Methods are: count = gets number of items in array objectAtIndex:i = returns element i of array (starting from 0)
64
NSArray – cycle through with for loop OPTION 2 NSDate *now = [NSDate date]; NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day //array of Dates NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday]; //get elements in array NSDate *first = [dateList objectAtIndex:0]; For(NSDate *d in dateList) { NSDAte *d = [dateList objectAtIndex:i]; NSLog(@” Date is %@”, d); } This is a “for in” loop --- convinient
65
NSMutableArray – changeable array of pointers to objects. NSMutableArray *thearray = [NSArray arrayWithObjects:o1,o2,o3,o4, nil]; //get element [thearray objectAtIndex:0]; //element at index 0 Example NSDate *now = [NSDate date]; NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day //array of Dates NSMutableArray *dateList = [NSMutableArray array]; //set elements [dateList addObject:now]; [dateList addObject:tomorrow]; [dateList addObject:yesterday]; Methods are: array = gets empty NSMutableArray addObject:obj = adds as next element the obj to array Note: you can add or remove a pointer from an NSMutableArray
66
NSMutableArray – adding element at Index location [arrayName insertObject:obj atIndex:i] Example -- put in at beginning of array [dateList insertObject:yesterday atIndex:0]
67
NSMutableArray – removing an element [arrayName removeObjectAtIndex:i] Example [dateList removeObjectAtIndex:0] //get rid of 1 st element
68
NSDictionary Immutable hash table. Look up objects using a key to get a value. + (id)dictionaryWithObjects:(NSArray *)values forKeys:(NSArray *)keys; + (id)dictionaryWithObjectsAndKeys:(id)firstObject,...; Creation example: NSDictionary *base = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:2], @“binary”, [NSNumber numberWithInt:16], @“hexadecimal”, nil]; Methods - (int)count; - (id)objectForKey:(id)key; - (NSArray *)allKeys; - (NSArray *)allValues; see documentation (apple.com) for more details
69
NSMutableDictionary Changeable + (id)dictionaryWithObjects:(NSArray *)values forKeys:(NSArray *)keys; + (id)dictionaryWithObjectsAndKeys:(id)firstObject,...; Creation : + (id)dictionary; //creates empty dictionary Methods - (void)setObject:(id)anObject forKey:(id)key; - (void)removeObjectForKey:(id)key; - (void)removeAllObjects; - (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary; see documentation (apple.com) for more details
70
NSMutableSet Changeable version of NSSet Methods - (void)addObject:(id)anObject; // does nothing if object that isEqual:anObject is already in - (void)removeObject:(id)anObject; - (void)unionSet:(NSSet *)otherSet; - (void)minusSet:(NSSet *)otherSet; - (void)intersectSet:(NSSet *)otherSet; see documentation (apple.com) for more details
71
Other useful Objective-C data classes NSOrderedSet, NSMutableOrderedSet
72
Cycling through Collections classes ---- use for-in loop Example: NSArray of NSString NSArray *myArray =...; for (NSString *string in myArray) { // no way for compiler to know what // myArray contains double value = [string doubleValue]; // crash HERE if string not an NSString }
73
NSSet example for-in loop Example: NSSet of id NSSet *mySet =...; for (id obj in mySet) { // do something with obj, but make sure you //don’t send it a message it does not respond to if ([obj isKindOfClass:[NSString class]]) { // send NSString messages to obj with impunity }
74
NSDictionary example for-in loop Example: NSDictionary NSDictionary *myDictionary =...; for (id key in myDictionary) { // grab value associated with the current key id value = [myDictionary objectForKey:key]; // do something with value here *** }
75
Property list (plist) A collection of collections Specifically, it is any graph of objects containing only the following classes: ○ NSArray, NSDictionary, NSNumber, NSString, NSDate, NSData Example1 : NSArray is a Property List if all its members are too --- NSArray of NSString is a Property List --- NSArray of NSArray as long as those NSArray’s members are Property Lists. Example 2: NSDictionary is one only if all keys and values are too Why define this term? Because the SDK has a number of methods which operate on Property Lists. Usually to read them from somewhere or write them out to somewhere. [plist writeToFile:(NSString *)path atomically:(BOOL)]; // plist is NSArray or NSDictionary We will see this in practice later
76
NSUserDefaults Lightweight storage of Property Lists. an NSDictionary that persists between launches of your application. Not a full-on database, so only store small things like user preferences.
77
NSUserDefaults continued Read and write via a shared instance obtained via class method standardUserDefaults [[NSUserDefaults standardUserDefaults] setArray:rvArray forKey:@“RecentlyViewed”]; Methods (some) - (void)setDouble:(double)aDouble forKey:(NSString *)key; - (NSInteger)integerForKey:(NSString *)key; // NSInteger is a typedef to 32 or 64 bit int - (void)setObject:(id)obj forKey:(NSString *)key; // obj must be a Property List - (NSArray *)arrayForKey:(NSString *)key; // will return nil if value for key is not NSArray Always remember to write the defaults out after each batch of changes! [[NSUserDefaults standardUserDefaults] synchronize];
79
CONCLUSION --- a note---Objective-C 2.0 – some features that were added In October 2007, Apple Inc. releases Objective-C 2.0 for Mac OS 10.5 (Leopard) Adds automatic garbage collection (ARC) Instance Methods (public functions) are defined differently using
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.