420 likes | 447 Views
Introduction to Objective-C (Overview, Data Types, NSLog, Classes). Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283. Overview. Objective-C is an object oriented language
E N D
Introduction to Objective-C (Overview, Data Types, NSLog, Classes) Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283
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 Typing • Dynamic Binding • Dynamic Linking
Inventors • Objective-C was invented by two men, Brad Cox and Tom Love • Both were introduced to Smalltalk at ITT(International Telephone & Telegraph) 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.
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”
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
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
Dynamic Language • Almost everything is done at runtime • Uses dynamic typing, linking, and binding • This allows for greater flexibility • Minimizes RAM and CPU usage
Objective-C • Is a SUPERSET of C
To Import or Include? #import <stdimport.h> • 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”
Primitive data types from C • Int , short , long • float , double • char
Operators same as C • + • - • * • / • ++ • --
Address and Pointers • Same as C • To get address of a variable I : &i • Pointer int *addressofi = &I;
Conditionals and Loops Same as C Conditionals • if / else if/ else • switch case Loops • for • while • do-while Branching • break • continue
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
Functions • Same as 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() }
Global and static variables • Same as C • Global variables defined at top of file • For static variables use keyword static before it static in CurrentYear = 2013;
Main Function –like C #import <whatever/what.h> 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 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
Non-GUI – text output • Two standard functions you see used • printf() – same as C printf(“Hello world”); //this is actual C code • NSLog() NSLog (@”Hello world”); // strictly Objective-C
Primitive data types • int, short, long • float,double • Char • BOOL = means boolean • Objective-C defines three of its own primitive types: id, Class, and SEL. These are the basis for Objective-C’s dynamic typing capabilities.
Foundation Data Types • NSComparator • NSDecimal • NSHashTableOptions • NSInteger • NSMapTableOptions • NSRange • NSRangePointer • NSSocketNativeHandle • NSStringEncoding • NSSwappedDouble • NSSwappedFloat • NSTimeInterval • NSUncaughtExceptionHandler • NSUInteger • NSZone
Classes • Objective-C abstracts a class’s interface from its implementation. • An interface declares the public properties and methods of a class (classname.h ) • The corresponding implementation defines the code that actually makes these properties and methods work (classname.m)
Class Declaration (.h file) • The declaration of a class begins with the compiler directive @interface and ends with the directive @end • They contain instance variable declarations in curly brackets {}, then method declarations • Interface has unimplemented method and variables. @interface ClassName : ItsSuperclass { instance variable declarations } property variables method declarations @end
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
Property Declaration • Properties offer a way to define the information that a class is intended to encapsulate. • Property declarations are included in the interface for a class. • A property declaration begins with the keyword @property @interface XYZPerson : NSObject @property NSString *firstName; @property NSString *lastName; @end • For variable declared with @property, compiler generates accessor methods (getter & setters) • The method used to access the value (the getter method) has the same name as the property. Eg The getter method for a property called firstName will also be called firstName. • The method used to set the value (the setter method) starts with the word “set” and then uses the capitalized property name. eg The setter method for a property called firstName will be called setFirstName:.
Property Declaration • Unless you specify otherwise, the synthesized instance variable has the same name as the property, but with an underscore prefix. • For a property called firstName, for example, the synthesized instance variable will be called _firstName. • To customize the name of accessor methods, it can specified as getter or setter attribute of @property. • @property (getter=isFinished) BOOL finished; • By default, a readwrite property will be backed by an instance variable.
Property Attributes • The readonly attribute is an easy way to make a property read-only. It omits the setter method and prevents assignment via dot-notation. • Atomic properties lock the underlying object to prevent this from happening, guaranteeing that the get or set operation is working with a complete value. • Properties declared with @property are atomic by default, and this does incur some overhead. • The strong attribute creates an owning relationship to whatever object is assigned to the property. This is the implicit behavior for all object properties
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
Whats this + and – stuff? • When declaring or implementing methods 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)
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
@sythesize • To customize the name of instance variable, it can specified by @synthesize in @implementation block of class @implementation YourClass @synthesize propertyName = instanceVariableName; ... @end • If you use @synthesize without specifying an instance variable name, like this: @synthesize firstName; • The instance variable will bear the same name as the property.
Object ---invoking a method, the basics • Objective-C uses a Message Approach • Invoke a method by placing the object and the desired method in square brackets, separated by a space. Arguments are separated from the method name using a colon: • When you have more than one parameter, it comes after the initial argument, following the same pattern. Each parameter is paired with a label, separated from other arguments by a space, and set off by a colon:
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. [Identifier message ] Like C++ or Java’s Identifier.message()
SETTING VALUES FOR CLASS VARIABLES OF AN OBJECT ---- THROUGH METHODS • [object methodName]; • [object setXXXMethod:value1]; • [object setYYYYMethod:value2];
Creating class instances Creating an Object ClassName *object = [[ClassName new]; 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