1 / 79

Objective-C

Toward iOS programming. Objective-C. 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. Inventors.

hmoss
Download Presentation

Objective-C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Toward iOS programming Objective-C

  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

  12. Objective C--- some basics

  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;

  16. Logic and functions and main()….

  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 NSLogconverts 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 <whatever/what.h> int main(intargc, 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 AutomaticReference Counting (kind of like automatic garbage collection) ----to handle getting rid of not needed items in memory (avoidingmemory leaks). YEAH! AUTOMATIC! -----like Java this way @autoreleasepool in a needed annotation around your mainblock 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 <whatever/what.h> int main(intargc, 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; } }

  25. Getting some output

  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

  27. Objective C---okay into the weird stuff --- Classes and messages

  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 <Cocoa/Cocoa.h> @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 <standardimports.h> #import “local-your-otherfiles.h” @interface ClassName: Parent { //class variables } //methods -(return_type) methodName:(type)param1, (type) param2; @end

  30. Declaring methods C++ syntax void function(int x, int y, char z); Object.function(x, y, z); Objective-C syntax -(void) method:(int)x, (int)y, (char)z; [Object function:x, y, z]; -(return type) function_name: (type) p1, (type) p2, ***; Apply function to Objectpassing 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 <Cocoa/Cocoa.h> @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 <Cocoa/Cocoa.h> @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

  36. How to create Objects

  37. Creating class instances Creating an Object 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

  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.

  46. Changing subjects –more on our Node class example ---lets create some child classes

  47. linkList class linkList.m #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 Class linkList is child of previous Node class (not showing .h file for brevity)

  48. Stack class (child of linkList) stack.h stack.m Remember alloc creates the object in memory #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 self is like the C++/Java word this.

  49. Example: main.m new is method defined in Stack class that simply that calls [Stack alloc] --- done for convinience #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]); printf("%d\t", [s pop]); [s release]; return 0; } release is method to release this object s explicitly from memory Run the program : 2 3 1 Note only need to import “stack.h” because stack imports LinkList.h which imports Node.h which imports cocoa.h

  50. Objective-C data types

More Related