OBJECTIVE-C FOR JAVADEVELOPERS
Key Points•   What is Objective-c?•   Syntax    o Type system    o Classes    o Message Passing    o Protocols    o Dynami...
What is Objective-c?•   Compiled, Object-Oriented and more    dynamic than Java.•   Objective-C was created in the early  ...
What is Objective-c? (cont.)•   Since Objective-c is a superset of C and    Java is a c-like language, so the syntax of   ...
What is Objective-c? (cont.)•   Objective-c uses different runtime model    than java.    o Java uses, VM and Class Loader...
Syntax: Type System•   Objective-c is a statically typed language (except    for id type) with the variable types declared...
Syntax: Type System (cont.)•   Follow C in which a local variable may be used    without initialization (compile error in ...
Syntax: Classes•   Objective-c is like java in that it is a class-    based Object-Oriented Programming    language.•   Cl...
Syntax: Classes (cont.)Class definition in java:// Component.javapublicclass Component{int comId;  String comNumber;public...
Syntax: Classes (cont.)Class definition in Objective-c:// Component.h@interface Component : NSObject{int comId;NSString*co...
Syntax: Classes (cont.)// Component.m#import "Component.h"@implementation Component-(id) init{/* implementation goes here*...
Syntax: Classes (cont.)•   In java each class is implicitly a child of    java.lang.Object, in Objective-c you have to    ...
Syntax: Classes (cont.)•   Object instantiation in Objective-c is a two steps    process. in java it done in one step://Ja...
Syntax: Classes (cont.)•   init implementation:- (id)init{self = [super init];    if (self) {// perform initialization of ...
Syntax: Message Passing•   Objective-c Uses smalltalk style messaging.•   In Objective-C one does not simply call a    met...
Syntax: Message Passing (cont.)•   The object to which the message receiver is    not guaranteed to respond to a message, ...
Syntax: Message Passing               (cont.)•   If messages are sent to nil (the null object    pointer), they will be si...
Syntax: Protocols•    The same concept as Interface in Java.•    Types of Protocols:      o Informal Protocols      o Form...
Syntax: Protocols (cont.)•   From Objective-c 2.0, Formal Protocols can    contains optional (@optional) methods.•   Infor...
Syntax: Protocols (cont.)Example on informat Protocols:•  Suppose we have a library that used to download a file   from a ...
Syntax: Dynamic Typing•    Objective-c is a statically typed language with     some dynamic typing support.•    An object ...
Syntax: Dynamic Typing (cont.)•   Dynamic Typing is used to compensate the    missing of Generics in Objective-c. (Java ha...
Syntax: Categories•   Similar to partial classes in C# but more    powerful.•   Add functionality to existing classes with...
Syntax: Categories (cont.)// NSString+NanPartNum.m@implementation NSString (NanPartNum)-(NSString*) nanPartNum{        ret...
Syntax: Categories (cont.)•   A category has full access to all of the    instance variables within the class, including  ...
Memory Management•   Objective-c 2.0 has a Garbage Collector but it    is not available in iOS (when writing mobile    app...
Memory Management (cont.)o   You should provide a dealloc method for each    object you create.    - (void) dealloc{      ...
Memory Management (cont.)   alloc (+1)       retain (+1)   release (-1)   release (-1)o You create an object as:      ins...
Memory Management (cont.)o For local variables, whenever you create an    object using alloc, release it using release or ...
Objective-c 2.0 features•   Properties•   Fast Enumerations
Questions?
Resources•   http://en.wikipedia.org/wiki/Objective-C•   http://www.gnustep.org/•   http://en.wikipedia.org/wiki/Java_(pro...
Upcoming SlideShare
Loading in...5
×

Objective-c for Java Developers

1,781

Published on

Published in: Technology, Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,781
On Slideshare
0
From Embeds
0
Number of Embeds
18
Actions
Shares
0
Downloads
27
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Objective-c for Java Developers"

  1. 1. OBJECTIVE-C FOR JAVADEVELOPERS
  2. 2. Key Points• What is Objective-c?• Syntax o Type system o Classes o Message Passing o Protocols o Dynamic Typing o Categories• Memory Management• Objective-c 2.0 features
  3. 3. What is Objective-c?• Compiled, Object-Oriented and more dynamic than Java.• Objective-C was created in the early 1980s.• Type system: static, dynamic, weak (Java: static, strong)• Objective-c = C + Smalltalk o Superset of C Programming language. (so, it is better to have a background knowledge
  4. 4. What is Objective-c? (cont.)• Since Objective-c is a superset of C and Java is a c-like language, so the syntax of most of the languages are the same (for,while,if,switch,brackets)• The Primary language for Cocoa API. (used in Mac OS X)• Major Implementations: GCC and Clang• Has a very rich Class APIs with two large APIs (Foundation and AppKit)
  5. 5. What is Objective-c? (cont.)• Objective-c uses different runtime model than java. o Java uses, VM and Class Loader.  .java => .class (bytecode) => ClassLoader load .class o Objective-c uses traditional C Linker model.  .m => .o (object file) => linker produces executable file. (also supports dynamic class loading using NSBundle class)
  6. 6. Syntax: Type System• Objective-c is a statically typed language (except for id type) with the variable types declared at compile-time.int x; float y; short s = 3;• have the same types as in C (machine depended, java have platform independent types:bool, int, long int, short int, long long int, float, double and long double.• Has 3 levels of variables, local, instance and global.• using global variables without caution may cause linking errors.
  7. 7. Syntax: Type System (cont.)• Follow C in which a local variable may be used without initialization (compile error in Java)• instance variables are initialized to nil (Objective- c null keyword)• static variables are not as in Java.• instance variables may use @public, @protected (default) or @private access modifiers.• Has no namespace concepts (Java has), and all classes are public.• String literals starts with @ ( @"BAV99")
  8. 8. Syntax: Classes• Objective-c is like java in that it is a class- based Object-Oriented Programming language.• Class declared in two files; interface (header) file (.h) and implementation file (.m).• In java, we declare the class in one .class file.• A common convention is to name the header file after the name of the class. (in java it should)
  9. 9. Syntax: Classes (cont.)Class definition in java:// Component.javapublicclass Component{int comId; String comNumber;public Component(){/* implementation goes here*/}publicvoid updateCompNumber(String newComNumber) {/* implementation goes here*/}publicvoid save(){/* implementation goes here*/}publicstatic Component addComponent (Component firstComp, Component secondComp){/* implementation goes here*/}}
  10. 10. Syntax: Classes (cont.)Class definition in Objective-c:// Component.h@interface Component : NSObject{int comId;NSString*comNumber;}-(id) init;-(void) updateCompNumber:(NSString*) newComNumber;-(void) save;+(Component*) addComponent:(Component*) firstComp to:(Component*) secondComp;@end
  11. 11. Syntax: Classes (cont.)// Component.m#import "Component.h"@implementation Component-(id) init{/* implementation goes here*/ return self;}-(void) updateCompNumber:(NSString*) newComNumber{/* implementation goes here*/}-(void) save { /* implementation goes here*/}+(Component*) addComponent:(Component*) firstComp to:(Component*) secondComp{/* implementation goes here*/}@end
  12. 12. Syntax: Classes (cont.)• In java each class is implicitly a child of java.lang.Object, in Objective-c you have to tell yourself what is the parent class.• NSObject is the parent of all classes in the class library• use NSObject if no other parent is needed.• Objective-c Has the concept of struct (inherited from c)
  13. 13. Syntax: Classes (cont.)• Object instantiation in Objective-c is a two steps process. in java it done in one step://Java Component c = new Component();// Objective-c Component* c = [[Component alloc] init];• No special operator for instantiation (new operator)• Both create Objects on Heap (vs stack objects)• Both follow the same pattern, first allocate memory for the new object then call the initialization method (init methods in Objective-c; Constructors in java)
  14. 14. Syntax: Classes (cont.)• init implementation:- (id)init{self = [super init]; if (self) {// perform initialization of object here } return self;}
  15. 15. Syntax: Message Passing• Objective-c Uses smalltalk style messaging.• In Objective-C one does not simply call a method; one sends a message.• In simula-style messaging languages, The method name is in most cases bound to a section of code in the target class by the compiler.• In Smalltalk (and Objective-C), the target of a message is resolved at runtime, with the receiving object itself interpreting the message.
  16. 16. Syntax: Message Passing (cont.)• The object to which the message receiver is not guaranteed to respond to a message, and if it does not, it simply raises an exception.• A method is identified by a selector or SEL and resolved to a C method pointer implementing it (an IMP). [obj method:argument]; Transformed at runtime to: method(obj, argument);
  17. 17. Syntax: Message Passing (cont.)• If messages are sent to nil (the null object pointer), they will be silently ignored or raise a generic exception, depending on compiler options. (default behaviour is to ignore)• Multi-parameter method take the form: -(type) metho:(type1) param1 dName:(type2)param2 -(void) add:(int) x to:(int)y So "add:to:" is the SEL name and called as: [MyObject add:10 to:30]
  18. 18. Syntax: Protocols• The same concept as Interface in Java.• Types of Protocols: o Informal Protocols o Formal Protocols• Formal Protocols is the same as interfaces in java, example: @protocol Locking -(void)lock; -(void)unlock; @end @interfaceSomeClass : SomeSuperClass <Locking> @end
  19. 19. Syntax: Protocols (cont.)• From Objective-c 2.0, Formal Protocols can contains optional (@optional) methods.• Informal Protocols used extensively in Cocoa API.• Common usage is to implement callbacks.
  20. 20. Syntax: Protocols (cont.)Example on informat Protocols:• Suppose we have a library that used to download a file from a URL: @interface DownloadHelper -(byte[]) download:(NSURL*) url target:(id)target; @end• This library documents that, the target object should supply a function with the following signature to be called when download complete: -(void)downloadComplete;• The Library come with a Category on NSObject with a default implementation for this method.
  21. 21. Syntax: Dynamic Typing• Objective-c is a statically typed language with some dynamic typing support.• An object can be sent a message that is not specified in its interface.• Dynamic typing on variables level is achieved using the id type. idanObject = [SomeClass someMethod]; [anObject doSomeMethod]; // no compile-time check if this method belongs to this type• Example: -(void)setMyValue:(id)foo; -(void)setMyValue:(id<aProtocol>)foo; -(void)setMyValue:(NSNumber*)foo;
  22. 22. Syntax: Dynamic Typing (cont.)• Dynamic Typing is used to compensate the missing of Generics in Objective-c. (Java has Generics) Java (No Generics): ArrayList arr = new ArrayList(); arr.add(new Employee()); Employee e = (Employee) arr.get(0); // should do cast which breaks concept of static typing Objective-c: NSMutableArray arr = [NSMutableArray array]; Employee* e1 = [[[Employee alloc]init]autorelease]; [arr addObject:e1]; Employee* e2 = [arr objectAtIndex:0]; // no cast needed• Containers in Objective-c uses id type for dynamic typing.
  23. 23. Syntax: Categories• Similar to partial classes in C# but more powerful.• Add functionality to existing classes without editing the source file.• extend classes at runtime (Java only supports compile-time inheritance)• Used extensively by Objective-c.• Example: extending the String class to allow get nanPartNumber from comPartNum // NSString+NanPartNum.h #import <Foundation/NSString.h> @interface NSString (NanPartNum) -(NSString*) nanPartNum;
  24. 24. Syntax: Categories (cont.)// NSString+NanPartNum.m@implementation NSString (NanPartNum)-(NSString*) nanPartNum{ return [self removeNonAlpha];}// other methods like removeNonAlpha@end// main.m#import <Foundation/NSString>#import "NSString+NanPartNum.h"int main(void){ NSString* comPartNumber = @"BAV99-70"; NSString nanPartNum = [comPartNumber nanPartNum]; // method resolved at runtime NSLog(@"%@", nanPartNum); /*prints BAV9970*/ }
  25. 25. Syntax: Categories (cont.)• A category has full access to all of the instance variables within the class, including private variables.• Overrides methods in the class with the same signature (can used to fix bugs in existing classes by rewriting its methods)• Used in Informal Protocols.• Cannot add variables in categories, just methods.• Other languages uses Prototype-oriented solutions to add functionality at runtime (e.g.:
  26. 26. Memory Management• Objective-c 2.0 has a Garbage Collector but it is not available in iOS (when writing mobile apps)• Manual memory management in Objective-c is much easier from C and C++.• Memory Management Rules: o If you create an object using the manual alloc style, you need to release the object later. o You should not manually release an autoreleased object. NSString* string2 = [[NSString alloc] init]; [string2 release];
  27. 27. Memory Management (cont.)o You should provide a dealloc method for each object you create. - (void) dealloc{ [instanceVar1 release]; [super dealloc]; }o Objective-C memory management system is called reference countingo Golden Rule: Simply, you alloc an object, maybe retain it at some point, then send one release for each alloc/retain you sent. So if you used alloc once and then retain once, you need to release twice.
  28. 28. Memory Management (cont.) alloc (+1) retain (+1) release (-1) release (-1)o You create an object as:  instance variable  function local variableo For Instance variables, make sure it is deallocated in the dealloc method (shown before) and when setting it just autorelease the old value and retain the new one. -(void) setPartNumber:(NSString*) partNum{ [self->partNum autorelease]; self->partNum = [partNum retain]; }
  29. 29. Memory Management (cont.)o For local variables, whenever you create an object using alloc, release it using release or autorelease, thats all.o Always remember, you are not the owner of objects you donot create!
  30. 30. Objective-c 2.0 features• Properties• Fast Enumerations
  31. 31. Questions?
  32. 32. Resources• http://en.wikipedia.org/wiki/Objective-C• http://www.gnustep.org/• http://en.wikipedia.org/wiki/Java_(programming_langua ge)• http://stackoverflow.com/questions/2010058• http://cocoadevcentral.com/d/learn_objectivec/
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×