Oct 21, 2014
Key Points
• What is Objective-c?
• Syntaxo Type systemo Classeso Message Passingo Protocolso Dynamic Typingo Categories
• Memory Management• Objective-c 2.0 features
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 + Smalltalko Superset of C Programming
language. (so, it is better to have a background knowledge with C first)
o Adds Smalltalk-style messaging to the C.
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)
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)
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.
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")
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)
Syntax: Classes (cont.)
Class definition in java:// Component.javapublic class Component{ int comId; String comNumber; public Component(){/* implementation goes here*/} public void updateCompNumber(String newComNumber) {/* implementation goes here*/} public void save(){/* implementation goes here*/} public static Component addComponent (Component firstComp, Component secondComp){/*
implementation goes here*/}}
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
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
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)
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)
• Both have GC (but iOS runtime doesn't provide GC).
Syntax: Classes (cont.)
• init implementation:
- (id)init { self = [super init]; if (self) { // perform initialization of object here } return self;}
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.
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);
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]
Syntax: Protocols
• The same concept as Interface in Java.
• Types of Protocols:o Informal Protocolso Formal Protocols
• Formal Protocols is the same as
interfaces in java, example:@protocol Locking
-(void)lock; -(void)unlock;
@end@interface SomeClass : SomeSuperClass <Locking>@end
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.
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.
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.id anObject = [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;- (void)setMyValue:(NSNumber<aProtocol> *)foo;
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 typingObjective-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.
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;@end
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*/ }
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.: Javascript)
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];
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 counting
o 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.
Memory Management (cont.)
o You create an object as: instance variable function local variable
o 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];
}
alloc (+1)retain (+1)
release (-1)
release (-1)
1 2 1 0
Memory Management (cont.)
o For local variables, whenever you create an object using alloc, release it using release or autorelease, that's all.
o Always remember, you are not the owner of objects you donot create!
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_(programming_language)
• http://stackoverflow.com/questions/2010058
• http://cocoadevcentral.com/d/learn_objectivec/