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. 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. 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. 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. 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. 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. 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)
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. 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. Syntax: Classes (cont.)
• init implementation:
- (id)init
{
self = [super init];
if (self) {
// perform initialization of object here
}
return self;
}
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. 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. 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. 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. 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. 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. 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. 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. 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;
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. 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. 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.
28. Memory Management (cont.)
alloc (+1) retain (+1) release (-1) release (-1)
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];
}
29. 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!