SlideShare a Scribd company logo
1 of 32
OBJECTIVE-C FOR JAVA
DEVELOPERS
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
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
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.java
publicclass 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*/}
}
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)
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 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
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.
     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;
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.
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;
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.:
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.)
   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];
  }
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_langua
    ge)
•   http://stackoverflow.com/questions/2010058
•   http://cocoadevcentral.com/d/learn_objectivec/

More Related Content

What's hot

Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#Sagar Pednekar
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classesyoavwix
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101kankemwa Ishaku
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924yohanbeschi
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 

What's hot (20)

JAVA BASICS
JAVA BASICSJAVA BASICS
JAVA BASICS
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
Introduction to java 101
Introduction to java 101Introduction to java 101
Introduction to java 101
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java8
Java8Java8
Java8
 
Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924Introduction to the Java bytecode - So@t - 20130924
Introduction to the Java bytecode - So@t - 20130924
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
JAVA BYTE CODE
JAVA BYTE CODEJAVA BYTE CODE
JAVA BYTE CODE
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Java Basics
Java BasicsJava Basics
Java Basics
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 

Similar to Objective-c for Java Developers

Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLou Loizides
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming IntroLou Loizides
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not JavaChris Adamson
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Bootstrapping iPhone Development
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone DevelopmentThoughtWorks
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 

Similar to Objective-c for Java Developers (20)

Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
Objective-C Is Not Java
Objective-C Is Not JavaObjective-C Is Not Java
Objective-C Is Not Java
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
Unit 1
Unit 1Unit 1
Unit 1
 
C#unit4
C#unit4C#unit4
C#unit4
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
 
Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 
Bootstrapping iPhone Development
Bootstrapping iPhone DevelopmentBootstrapping iPhone Development
Bootstrapping iPhone Development
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 
CS8392 OOP
CS8392 OOPCS8392 OOP
CS8392 OOP
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 

Recently uploaded

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Recently uploaded (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Objective-c for Java Developers

  • 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)
  • 9. Syntax: Classes (cont.) Class definition in java: // Component.java publicclass 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. 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. 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. 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;
  • 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. 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!
  • 30. Objective-c 2.0 features • Properties • Fast Enumerations
  • 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/