SlideShare a Scribd company logo
Objective-C for
                           Java Developers
                                   http://bobmccune.com




Tuesday, August 10, 2010
Objective-C Overview




Tuesday, August 10, 2010
Objective-C
                 The old new hotness
                    • Strict superset of ANSI C
                           • Object-oriented extensions
                           • Additional syntax and types
                    • Native Mac & iOS development language
                    • Flexible typing
                    • Simple, expressive syntax
                    • Dynamic runtime


Tuesday, August 10, 2010
Why Use Objective-C?
                 No Java love from Apple?
                    • Key to developing for Mac & iOS platforms
                    • Performance
                           • Continually optimized runtime environment
                             • Can optimize down to C as needed
                           • Memory Management
                    • Dynamic languages provide greater flexibility
                           • Cocoa APIs rely heavily on these features


Tuesday, August 10, 2010
Java Developer’s Concerns
                Ugh, didn’t Java solve all of this stuff
                    • Pointers
                    • Memory Management
                    • Preprocessing & Linking
                    • No Namespaces
                           • Prefixes used to avoid collisions
                           • Common Prefixes: NS, UI, CA, MK, etc.



Tuesday, August 10, 2010
Creating Classes




Tuesday, August 10, 2010
Classes
                    • Classes define the blueprint for objects.
                    • Objective-C class definitions are separated
                           into an interface and an implementation.
                           • Usually defined in separate .h and .m files
                                    •Defines the            •Defines the actual
                                     programming            implementation
                                     interface              code

                                    •Defines the             •Defines one or
                                     object's instance      more initializers
                                     variable               to properly
                                                            initialize and
                                                            object instance




Tuesday, August 10, 2010
Defining the class interface
                  @interface BankAccount : NSObject {
                    float accountBalance;
                    NSString *accountNumber;
                  }

                  - (float)withDraw:(float)amount;
                  - (void)deposit:(float)amount;
                  @end




Tuesday, August 10, 2010
Defining the class interface
                  @interface BankAccount : NSObject {
                    float accountBalance;
                    NSString *accountNumber;
                  }

                  - (float)withDraw:(float)amount;
                  - (void)deposit:(float)amount;
                  @end




Tuesday, August 10, 2010
Defining the class interface
                  @interface BankAccount : NSObject {
                    float accountBalance;
                    NSString *accountNumber;
                  }

                  - (float)withDraw:(float)amount;
                  - (void)deposit:(float)amount;
                  @end




Tuesday, August 10, 2010
Defining the class interface
                  @interface BankAccount : NSObject {
                    float accountBalance;
                    NSString *accountNumber;
                  }

                  - (float)withDraw:(float)amount;
                  - (void)deposit:(float)amount;
                  @end




Tuesday, August 10, 2010
Defining the class interface
                  @interface BankAccount : NSObject {
                    float accountBalance;
                    NSString *accountNumber;
                  }

                  - (float)withDraw:(float)amount;
                  - (void)deposit:(float)amount;
                  @end




Tuesday, August 10, 2010
Defining the class interface
                  @interface BankAccount : NSObject {
                    float accountBalance;
                    NSString *accountNumber;
                  }

                  - (float)withDraw:(float)amount;
                  - (void)deposit:(float)amount;
                  @end




Tuesday, August 10, 2010
Defining the class implementation
                   #import "BankAccount.h"

                   @implementation BankAccount

                   - (id)init {
                     self = [super init];
                     return self;
                   }

                   - (float)withdraw:(float)amount {
                     // calculate valid withdrawal
                   	 return amount;
                   }

                   - (void)deposit:(float)amount {
                        // record transaction
                   }
                   @end


Tuesday, August 10, 2010
Defining the class implementation
                   #import "BankAccount.h"

                   @implementation BankAccount

                   - (id)init {
                     self = [super init];
                     return self;
                   }

                   - (float)withdraw:(float)amount {
                     // calculate valid withdrawal
                   	 return amount;
                   }

                   - (void)deposit:(float)amount {
                        // record transaction
                   }
                   @end


Tuesday, August 10, 2010
Defining the class implementation
                   #import "BankAccount.h"

                   @implementation BankAccount

                   - (id)init {
                     self = [super init];
                     return self;
                   }

                   - (float)withdraw:(float)amount {
                     // calculate valid withdrawal
                   	 return amount;
                   }

                   - (void)deposit:(float)amount {
                        // record transaction
                   }
                   @end


Tuesday, August 10, 2010
Defining the class implementation
                   #import "BankAccount.h"

                   @implementation BankAccount

                   - (id)init {
                     self = [super init];
                     return self;
                   }

                   - (float)withdraw:(float)amount {
                     // calculate valid withdrawal
                   	 return amount;
                   }

                   - (void)deposit:(float)amount {
                        // record transaction
                   }
                   @end


Tuesday, August 10, 2010
Working with Objects




Tuesday, August 10, 2010
Creating Objects
                 From blueprint to reality
                  • No concept of constructors in Objective-C
                  • Regular methods create new instances
                           • Allocation and initialization are performed
                            separately
                             • Provides flexibility in where an object is allocated
                             • Provides flexibility in how an object is initialized
                    Java
                   BankAccount account = new BankAccount();

                   Objective C
                   BankAccount *account = [[BankAccount alloc] init];


Tuesday, August 10, 2010
Creating Objects
                • NSObject defines class method called alloc
                      • Dynamically allocates memory for object
                      • Returns new instance of receiving class
                           BankAccount *account = [BankAccount alloc];

                • NSObject defines instance method init
                      • Implemented by subclasses to initialize instance after memory
                           for it has been allocated
                      • Subclasses commonly define several initializers
                           account = [account init];

                •    alloc     and init calls are almost always nested into single line
                           BankAccount *account = [[BankAccount alloc] init];



Tuesday, August 10, 2010
Methods
                 • Classes can define both class and instance methods
                 • Methods are always public.
                   • “Private” methods defined in implementation
                 • Class methods (prefixed with +):
                       • Define behaviors associated with class, not particular
                           instance
                       •   No access to instance variables
                 • Instance methods (prefixed with -)
                       • Define behaviors specific to particular instance
                       • Manage object state
                 • Methods invoked by passing messages...
Tuesday, August 10, 2010
Messages
                 Speaking to objects
                  • Methods are invoked by passing messages
                           • Done indirectly. We never directly invoke
                               methods
                           •   Messages dynamically bound to method
                               implementations at runtime
                           •   Dispatching handled by runtime environment
                    • Simple messages take the form:
                           •




                               [object message];

                    • Can pass one or more arguments:
                           •




                               [object messageWithArg1:arg1 arg2:arg2];


Tuesday, August 10, 2010
self          and super
                    • Methods have implicit reference to owning
                      object called self (similar to Java’s this)
                    • Additionally have access to superclass
                      methods using super

                           -(id)init {
                              if (self = [super init]) {
                                 // do initialization
                              }
                              return self;
                           }

Tuesday, August 10, 2010
Invoking methods in Java
                Map person = new HashMap();

                person.put("name", "Joe Smith");
                String address = "123 Street";
                String house = address.substring(0, 3);
                person.put("houseNumber", house);

                List children = Arrays.asList("Sue", "Tom");
                person.put("children", children);




Tuesday, August 10, 2010
Invoking methods in Objective-C
                NSMutableDictionary *person =
                     [NSMutableDictionary dictionary];

                [person setObject:@"Joe Smith" forKey:@"name"];

                NSString *address = @"123 Street";
                NSString *house =
                    [address substringWithRange:NSMakeRange(0, 3)];
                [person setObject:house forKey:@"houseNumber"];

                NSArray *children =
                   [NSArray arrayWithObjects:@"Sue", @"Tom", nil];

                [person setObject:children forKey:@"children"];




Tuesday, August 10, 2010
Memory Management




Tuesday, August 10, 2010
Memory Management
                 Dude, where’s my Garbage Collection?
                 • Garbage collection available for Mac apps (10.5+)
                   • Use it if targeting 10.5+!
                   • Use explicit memory management if targeting
                        <= 10.4
                 •    No garbage collection on iOS due to performance
                      concerns.
                 •    Memory managed using simple reference counting
                      mechanism:
                      • Higher level abstraction than malloc / free
                       • Straightforward approach, but must adhere to
                           conventions and rules

Tuesday, August 10, 2010
Memory Management
                 Reference Counting
                    • Objective-C objects are reference counted
                           • Objects start with reference count of 1
                           • Increased with retain
                           • Decreased with release, autorelease
                           • When count equals 0, runtime invokes dealloc
                                      1            2             1             0
                              alloc       retain       release       release




Tuesday, August 10, 2010
Memory Management
                   Understanding the rules
                   • Implicitly retain any object you create using:
                           Methods starting with "alloc", "new", or contains "copy"
                           e.g alloc, allocWithZone, newObject, mutableCopy,etc.
                    • If you've retained it, you must release it
                    • Many objects provide convenience methods
                      that return an autoreleased reference.
                    • Holding object reference from these
                      methods does not make you the retainer
                      • However, if you retain it you need an
                        offsetting release or autorelease to free it

Tuesday, August 10, 2010
retain / release / autorelease
                 @implementation BankAccount

                 - (NSString *)accountNumber {
                     return [[accountNumber retain] autorelease];
                 }

                 - (void)setAccountNumber:(NSString *)newNumber {
                     if (accountNumber != newNumber) {
                         [accountNumber release];
                         accountNumber = [newNumber retain];
                     }
                 }

                 - (void)dealloc {
                     [self setAccountNumber:nil];
                     [super dealloc];
                 }

                 @end
Tuesday, August 10, 2010
Properties




Tuesday, August 10, 2010
Properties
                 Simplifying Accessors
                  • Object-C 2.0 introduced new syntax for defining
                       accessor code
                           • Much less verbose, less error prone
                           • Highly configurable
                           • Automatically generates accessor code
                  • Compliments existing conventions and technologies
                           •   Key-Value Coding (KVC)
                           •   Key-Value Observing (KVO)
                           •   Cocoa Bindings
                           •   Core Data


Tuesday, August 10, 2010
Properties: Interface
               @property(attributes) type variable;

                             Attribute      Impacts
                 readonly/readwrite         Mutability

                  assign/retain/copy         Storage

                             nonatomic     Concurrency

                           setter/getter       API



Tuesday, August 10, 2010
Properties: Interface
               @property(attributes) type variable;

                             Attribute      Impacts
                 readonly/readwrite         Mutability

                  assign/retain/copy         Storage

                             nonatomic     Concurrency

                           setter/getter       API

                @property(readonly) NSString *acctNumber;

Tuesday, August 10, 2010
Properties: Interface
               @property(attributes) type variable;

                             Attribute       Impacts
                 readonly/readwrite         Mutability

                  assign/retain/copy         Storage

                             nonatomic     Concurrency

                           setter/getter       API

                @property(readwrite, copy) NSString *acctNumber;


Tuesday, August 10, 2010
Properties: Interface
               @property(attributes) type variable;

                             Attribute      Impacts
                 readonly/readwrite         Mutability

                  assign/retain/copy         Storage

                             nonatomic     Concurrency

                           setter/getter       API

                @property(nonatomic, retain) NSDate *activeOn;

Tuesday, August 10, 2010
Properties: Interface
               @property(attributes) type variable;

                             Attribute         Impacts
                 readonly/readwrite            Mutability

                  assign/retain/copy            Storage

                             nonatomic       Concurrency

                           setter/getter          API

                @property(readonly, getter=username) NSString *name;


Tuesday, August 10, 2010
Properties: Interface
                @interface BankAccount : NSObject {
                    NSString *accountNumber;
                    NSDecimalNumber *balance;
                    NSDecimalNumber *fees;
                    BOOL accountCurrent;
                }

                @property(readwrite, copy) NSString *accountNumber;
                @property(readwrite, retain) NSDecimalNumber *balance;
                @property(readonly) NSDecimalNumber *fees;
                @property(getter=isCurrent) BOOL accountCurrent;

                @end




Tuesday, August 10, 2010
Properties: Interface
                                                         New in 10.6
                @interface BankAccount : NSObject {       and iOS 4
                  // Look ma, no more ivars
                }

                @property(readwrite, copy) NSString *accountNumber;
                @property(readwrite, retain) NSDecimalNumber *balance;
                @property(readonly) NSDecimalNumber *fees;
                @property(getter=isCurrent) BOOL accountCurrent;

                @end




Tuesday, August 10, 2010
Properties: Implementation
                @implementation BankAccount

                @synthesize   accountNumber;
                @synthesize   balance;
                @synthesize   fees;
                @synthesize   accountCurrent;

                ...

                @end



Tuesday, August 10, 2010
Properties: Implementation
               @implementation BankAccount    New in 10.6
                                               and iOS 4

               // no more @synthesize statements

               ...

               @end




Tuesday, August 10, 2010
Accessing Properties
                    • Generated properties are standard methods
                    • Accessed through normal messaging syntax
                           [object property];
                           [object setProperty:(id)newValue];

                    • Objective-C 2.0 property access via dot syntax
                           object.property;
                           object.property = newValue;


                           Dot notation is just syntactic sugar. Still uses accessor
                           methods. Doesn't get/set values directly.

Tuesday, August 10, 2010
Protocols




Tuesday, August 10, 2010
Protocols
                 Java’s Interface done Objective-C style
                • List of method declarations
                      • Not associated with a particular class
                      • Conformance, not class, is important
                • Useful in defining:
                      • Methods that others are expected to
                           implement
                      •    Declaring an interface while hiding its particular
                           class
                      •    Capturing similarities among classes that aren't
                           hierarchically related


Tuesday, August 10, 2010
Protocols
                NSCoding            NSObject              NSCoding




                           Person              Account




                              CheckingAccount       SavingAccount




Tuesday, August 10, 2010
Defining a Protocol
                NSCoding from Foundation Framework
                Objective-C equivalent to java.io.Externalizable

                @protocol NSCoding

                - (void)encodeWithCoder:(NSCoder *)aCoder;
                - (id)initWithCoder:(NSCoder *)aDecoder;

                @end




Tuesday, August 10, 2010
Adopting a Protocol
                @interface   Person : NSObject <NSCoding> {
                  NSString   *name;
                  NSString   *street;
                  NSString   *city, *state, *zip;
                }

                // method declarations

                @end




Tuesday, August 10, 2010
Conforming to a Protocol
                    Partial implementation of conforming Person class
                   @implementation Person

                   -(id)initWithCoder:(NSCoder *)coder {
                   	 if (self = [super init]) {
                   	 	 name = [coder decodeObjectForKey:@"name"];
                   	 	 [name retain];
                   	 }
                   	 return self;
                   }

                   -(void)encodeWithCoder:(NSCoder *)coder {
                   	 [coder encodeObject:name forKey:@"name"];
                   }

                   @end


Tuesday, August 10, 2010
@required                and @optional
                    • Protocols methods are required by default
                    • Can be relaxed with @optional directive
                           @protocol SomeProtocol

                           - (void)requiredMethod;

                           @optional
                           - (void)anOptionalMethod;
                           - (void)anotherOptionalMethod;

                           @required
                           - (void)anotherRequiredMethod;

                           @end

Tuesday, August 10, 2010
Categories & Extensions




Tuesday, August 10, 2010
Categories
                 Extending Object Features
                  • Add new methods to existing classes
                           •   Alternative to subclassing
                           •   Defines new methods and can override existing
                           •   Does not define new instance variables
                           •   Becomes part of the class definition
                               • Inherited by subclasses
                    • Can be used as organizational tool
                    • Often used in defining "private" methods


Tuesday, August 10, 2010
Using Categories
                 Interface
                 @interface NSString (Extensions)
                 -(NSString *)trim;
                 @end

                 Implementation
                 @implementation NSString (Extensions)
                 -(NSString *)trim {
                    NSCharacterSet *charSet =
                       [NSCharacterSet whitespaceAndNewlineCharacterSet];
                 	 return [self stringByTrimmingCharactersInSet:charSet];
                 }
                 @end

                 Usage
                 NSString *string = @"   A string to be trimmed    ";
                 NSLog(@"Trimmed string: '%@'", [string trim]);



Tuesday, August 10, 2010
Class Extensions
                 Unnamed Categories
                  • Objective-C 2.0 adds ability to define
                    "anonymous" categories
                           • Category is unnamed
                           • Treated as class interface continuations
                    • Useful for implementing required "private" API
                    • Compiler enforces methods are implemented




Tuesday, August 10, 2010
Class Extensions
                 Example
                 @interface Person : NSObject {
                 	 NSString *name;
                 }
                 -(NSString *)name;

                 @end




Tuesday, August 10, 2010
Class Extensions
                 Example
                 @interface Person ()
                 -(void)setName:(NSString *)newName;
                 @end

                 @implementation Person
                 - (NSString *)name {
                 	 return name;
                 }

                 - (void)setName:(NSString *)newName {
                 	 name = newName;
                 }
                 @end
Tuesday, August 10, 2010
Summary




Tuesday, August 10, 2010
Objective-C
                 Summary
                  • Fully C, Fully Object-Oriented
                  • Powerful dynamic runtime
                  • Objective-C 2.0 added many useful new
                    features
                           • Garbage Collection for Mac OS X apps
                           • Properties, Improved Categories & Protocols
                    • Objective-C 2.1 continues its evolution:
                           • Blocks (Closures)
                           • Synthesize by default for properties

Tuesday, August 10, 2010
Questions?




Tuesday, August 10, 2010

More Related Content

What's hot

Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
Ingvar Stepanyan
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」techtalkdwango
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
Jarrod Overson
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
Learn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryLearn JS concepts by implementing jQuery
Learn JS concepts by implementing jQuery
Wingify Engineering
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
Doris Chen
 
Your code is not a string
Your code is not a stringYour code is not a string
Your code is not a string
Ingvar Stepanyan
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
Sultan Khan
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
Mithun T. Dhar
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Modernize your Objective-C
Modernize your Objective-CModernize your Objective-C
Modernize your Objective-C
Massimo Oliviero
 

What's hot (20)

Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 
Core concepts-javascript
Core concepts-javascriptCore concepts-javascript
Core concepts-javascript
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Learn JS concepts by implementing jQuery
Learn JS concepts by implementing jQueryLearn JS concepts by implementing jQuery
Learn JS concepts by implementing jQuery
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Your code is not a string
Your code is not a stringYour code is not a string
Your code is not a string
 
Javascript
JavascriptJavascript
Javascript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Modernize your Objective-C
Modernize your Objective-CModernize your Objective-C
Modernize your Objective-C
 

Viewers also liked

Core Animation
Core AnimationCore Animation
Core Animation
Bob McCune
 
Drawing with Quartz on iOS
Drawing with Quartz on iOSDrawing with Quartz on iOS
Drawing with Quartz on iOS
Bob McCune
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View Controllers
Bob McCune
 
Composing and Editing Media with AV Foundation
Composing and Editing Media with AV FoundationComposing and Editing Media with AV Foundation
Composing and Editing Media with AV Foundation
Bob McCune
 
Quartz 2D with Swift 3
Quartz 2D with Swift 3Quartz 2D with Swift 3
Quartz 2D with Swift 3
Bob McCune
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV Foundation
Bob McCune
 
Designing better user interfaces
Designing better user interfacesDesigning better user interfaces
Designing better user interfaces
Johan Ronsse
 
iOS design: a case study
iOS design: a case studyiOS design: a case study
iOS design: a case study
Johan Ronsse
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
John Wilker
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngine
Bob McCune
 
iOS Developer Overview - DevWeek 2014
iOS Developer Overview - DevWeek 2014iOS Developer Overview - DevWeek 2014
iOS Developer Overview - DevWeek 2014
Paul Ardeleanu
 
Tuning Android Applications (Part One)
Tuning Android Applications (Part One)Tuning Android Applications (Part One)
Tuning Android Applications (Part One)
CommonsWare
 
Android performance tuning. Memory.
Android performance tuning. Memory.Android performance tuning. Memory.
Android performance tuning. Memory.
Sergii Kozyrev
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV Foundation
Chris Adamson
 
Deep Parameters Tuning for Android Mobile Apps
Deep Parameters Tuning for Android Mobile AppsDeep Parameters Tuning for Android Mobile Apps
Deep Parameters Tuning for Android Mobile Apps
Davide De Chiara
 
Objective-C for Java developers
Objective-C for Java developersObjective-C for Java developers
Objective-C for Java developers
Fábio Bernardo
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Haribabu Nandyal Padmanaban
 
Introduction to ART (Android Runtime)
Introduction to ART (Android Runtime)Introduction to ART (Android Runtime)
Introduction to ART (Android Runtime)
Iordanis (Jordan) Giannakakis
 
Animation in iOS
Animation in iOSAnimation in iOS
Animation in iOS
Alexis Goldstein
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questions
Arc & Codementor
 

Viewers also liked (20)

Core Animation
Core AnimationCore Animation
Core Animation
 
Drawing with Quartz on iOS
Drawing with Quartz on iOSDrawing with Quartz on iOS
Drawing with Quartz on iOS
 
Creating Container View Controllers
Creating Container View ControllersCreating Container View Controllers
Creating Container View Controllers
 
Composing and Editing Media with AV Foundation
Composing and Editing Media with AV FoundationComposing and Editing Media with AV Foundation
Composing and Editing Media with AV Foundation
 
Quartz 2D with Swift 3
Quartz 2D with Swift 3Quartz 2D with Swift 3
Quartz 2D with Swift 3
 
Master Video with AV Foundation
Master Video with AV FoundationMaster Video with AV Foundation
Master Video with AV Foundation
 
Designing better user interfaces
Designing better user interfacesDesigning better user interfaces
Designing better user interfaces
 
iOS design: a case study
iOS design: a case studyiOS design: a case study
iOS design: a case study
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
Building Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngineBuilding Modern Audio Apps with AVAudioEngine
Building Modern Audio Apps with AVAudioEngine
 
iOS Developer Overview - DevWeek 2014
iOS Developer Overview - DevWeek 2014iOS Developer Overview - DevWeek 2014
iOS Developer Overview - DevWeek 2014
 
Tuning Android Applications (Part One)
Tuning Android Applications (Part One)Tuning Android Applications (Part One)
Tuning Android Applications (Part One)
 
Android performance tuning. Memory.
Android performance tuning. Memory.Android performance tuning. Memory.
Android performance tuning. Memory.
 
Mastering Media with AV Foundation
Mastering Media with AV FoundationMastering Media with AV Foundation
Mastering Media with AV Foundation
 
Deep Parameters Tuning for Android Mobile Apps
Deep Parameters Tuning for Android Mobile AppsDeep Parameters Tuning for Android Mobile Apps
Deep Parameters Tuning for Android Mobile Apps
 
Objective-C for Java developers
Objective-C for Java developersObjective-C for Java developers
Objective-C for Java developers
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Introduction to ART (Android Runtime)
Introduction to ART (Android Runtime)Introduction to ART (Android Runtime)
Introduction to ART (Android Runtime)
 
Animation in iOS
Animation in iOSAnimation in iOS
Animation in iOS
 
20 iOS developer interview questions
20 iOS developer interview questions20 iOS developer interview questions
20 iOS developer interview questions
 

Similar to Objective-C for Java Developers

Beginningi os part1-bobmccune
Beginningi os part1-bobmccuneBeginningi os part1-bobmccune
Beginningi os part1-bobmccune
Mobile March
 
NeXTPLAN: Enterprise software that rocks!
NeXTPLAN: Enterprise software that rocks!NeXTPLAN: Enterprise software that rocks!
NeXTPLAN: Enterprise software that rocks!
ESUG
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
SantoshVarshney3
 
NeXTPLAN
NeXTPLANNeXTPLAN
NeXTPLAN
jbrichau
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
Petr Dvorak
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
iPhone Programming in 30 minutes (?) [FTS]
iPhone Programming in 30 minutes (?) [FTS]iPhone Programming in 30 minutes (?) [FTS]
iPhone Programming in 30 minutes (?) [FTS]
Diego Pizzocaro
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
Tunvir Rahman Tusher
 
02 objective-c session 2
02  objective-c session 202  objective-c session 2
02 objective-c session 2
Amr Elghadban (AmrAngry)
 
iOS
iOSiOS
MacRuby & RubyMotion - Madridrb May 2012
MacRuby & RubyMotion - Madridrb May 2012MacRuby & RubyMotion - Madridrb May 2012
MacRuby & RubyMotion - Madridrb May 2012Mark Villacampa
 
iOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEEiOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEE
Hendrik Ebel
 
My Adventures In Objective-C (A Rubyists Perspective)
My Adventures In Objective-C (A Rubyists Perspective)My Adventures In Objective-C (A Rubyists Perspective)
My Adventures In Objective-C (A Rubyists Perspective)
abdels
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)
Altece
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
Luis Azevedo
 
Irving iOS Jumpstart Meetup - Objective-C Session 2
Irving iOS Jumpstart Meetup - Objective-C Session 2Irving iOS Jumpstart Meetup - Objective-C Session 2
Irving iOS Jumpstart Meetup - Objective-C Session 2
irving-ios-jumpstart
 

Similar to Objective-C for Java Developers (20)

Beginningi os part1-bobmccune
Beginningi os part1-bobmccuneBeginningi os part1-bobmccune
Beginningi os part1-bobmccune
 
NeXTPLAN: Enterprise software that rocks!
NeXTPLAN: Enterprise software that rocks!NeXTPLAN: Enterprise software that rocks!
NeXTPLAN: Enterprise software that rocks!
 
Iphone course 1
Iphone course 1Iphone course 1
Iphone course 1
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
NeXTPLAN
NeXTPLANNeXTPLAN
NeXTPLAN
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
iPhone Programming in 30 minutes (?) [FTS]
iPhone Programming in 30 minutes (?) [FTS]iPhone Programming in 30 minutes (?) [FTS]
iPhone Programming in 30 minutes (?) [FTS]
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
 
02 objective-c session 2
02  objective-c session 202  objective-c session 2
02 objective-c session 2
 
iOS
iOSiOS
iOS
 
MacRuby & RubyMotion - Madridrb May 2012
MacRuby & RubyMotion - Madridrb May 2012MacRuby & RubyMotion - Madridrb May 2012
MacRuby & RubyMotion - Madridrb May 2012
 
iOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEEiOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEE
 
My Adventures In Objective-C (A Rubyists Perspective)
My Adventures In Objective-C (A Rubyists Perspective)My Adventures In Objective-C (A Rubyists Perspective)
My Adventures In Objective-C (A Rubyists Perspective)
 
XQuery Design Patterns
XQuery Design PatternsXQuery Design Patterns
XQuery Design Patterns
 
iOS Basic
iOS BasiciOS Basic
iOS Basic
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)Objective-C A Beginner's Dive (with notes)
Objective-C A Beginner's Dive (with notes)
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
Irving iOS Jumpstart Meetup - Objective-C Session 2
Irving iOS Jumpstart Meetup - Objective-C Session 2Irving iOS Jumpstart Meetup - Objective-C Session 2
Irving iOS Jumpstart Meetup - Objective-C Session 2
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 

Objective-C for Java Developers

  • 1. Objective-C for Java Developers http://bobmccune.com Tuesday, August 10, 2010
  • 3. Objective-C The old new hotness • Strict superset of ANSI C • Object-oriented extensions • Additional syntax and types • Native Mac & iOS development language • Flexible typing • Simple, expressive syntax • Dynamic runtime Tuesday, August 10, 2010
  • 4. Why Use Objective-C? No Java love from Apple? • Key to developing for Mac & iOS platforms • Performance • Continually optimized runtime environment • Can optimize down to C as needed • Memory Management • Dynamic languages provide greater flexibility • Cocoa APIs rely heavily on these features Tuesday, August 10, 2010
  • 5. Java Developer’s Concerns Ugh, didn’t Java solve all of this stuff • Pointers • Memory Management • Preprocessing & Linking • No Namespaces • Prefixes used to avoid collisions • Common Prefixes: NS, UI, CA, MK, etc. Tuesday, August 10, 2010
  • 7. Classes • Classes define the blueprint for objects. • Objective-C class definitions are separated into an interface and an implementation. • Usually defined in separate .h and .m files •Defines the •Defines the actual programming implementation interface code •Defines the •Defines one or object's instance more initializers variable to properly initialize and object instance Tuesday, August 10, 2010
  • 8. Defining the class interface @interface BankAccount : NSObject { float accountBalance; NSString *accountNumber; } - (float)withDraw:(float)amount; - (void)deposit:(float)amount; @end Tuesday, August 10, 2010
  • 9. Defining the class interface @interface BankAccount : NSObject { float accountBalance; NSString *accountNumber; } - (float)withDraw:(float)amount; - (void)deposit:(float)amount; @end Tuesday, August 10, 2010
  • 10. Defining the class interface @interface BankAccount : NSObject { float accountBalance; NSString *accountNumber; } - (float)withDraw:(float)amount; - (void)deposit:(float)amount; @end Tuesday, August 10, 2010
  • 11. Defining the class interface @interface BankAccount : NSObject { float accountBalance; NSString *accountNumber; } - (float)withDraw:(float)amount; - (void)deposit:(float)amount; @end Tuesday, August 10, 2010
  • 12. Defining the class interface @interface BankAccount : NSObject { float accountBalance; NSString *accountNumber; } - (float)withDraw:(float)amount; - (void)deposit:(float)amount; @end Tuesday, August 10, 2010
  • 13. Defining the class interface @interface BankAccount : NSObject { float accountBalance; NSString *accountNumber; } - (float)withDraw:(float)amount; - (void)deposit:(float)amount; @end Tuesday, August 10, 2010
  • 14. Defining the class implementation #import "BankAccount.h" @implementation BankAccount - (id)init { self = [super init]; return self; } - (float)withdraw:(float)amount { // calculate valid withdrawal return amount; } - (void)deposit:(float)amount { // record transaction } @end Tuesday, August 10, 2010
  • 15. Defining the class implementation #import "BankAccount.h" @implementation BankAccount - (id)init { self = [super init]; return self; } - (float)withdraw:(float)amount { // calculate valid withdrawal return amount; } - (void)deposit:(float)amount { // record transaction } @end Tuesday, August 10, 2010
  • 16. Defining the class implementation #import "BankAccount.h" @implementation BankAccount - (id)init { self = [super init]; return self; } - (float)withdraw:(float)amount { // calculate valid withdrawal return amount; } - (void)deposit:(float)amount { // record transaction } @end Tuesday, August 10, 2010
  • 17. Defining the class implementation #import "BankAccount.h" @implementation BankAccount - (id)init { self = [super init]; return self; } - (float)withdraw:(float)amount { // calculate valid withdrawal return amount; } - (void)deposit:(float)amount { // record transaction } @end Tuesday, August 10, 2010
  • 18. Working with Objects Tuesday, August 10, 2010
  • 19. Creating Objects From blueprint to reality • No concept of constructors in Objective-C • Regular methods create new instances • Allocation and initialization are performed separately • Provides flexibility in where an object is allocated • Provides flexibility in how an object is initialized Java BankAccount account = new BankAccount(); Objective C BankAccount *account = [[BankAccount alloc] init]; Tuesday, August 10, 2010
  • 20. Creating Objects • NSObject defines class method called alloc • Dynamically allocates memory for object • Returns new instance of receiving class BankAccount *account = [BankAccount alloc]; • NSObject defines instance method init • Implemented by subclasses to initialize instance after memory for it has been allocated • Subclasses commonly define several initializers account = [account init]; • alloc and init calls are almost always nested into single line BankAccount *account = [[BankAccount alloc] init]; Tuesday, August 10, 2010
  • 21. Methods • Classes can define both class and instance methods • Methods are always public. • “Private” methods defined in implementation • Class methods (prefixed with +): • Define behaviors associated with class, not particular instance • No access to instance variables • Instance methods (prefixed with -) • Define behaviors specific to particular instance • Manage object state • Methods invoked by passing messages... Tuesday, August 10, 2010
  • 22. Messages Speaking to objects • Methods are invoked by passing messages • Done indirectly. We never directly invoke methods • Messages dynamically bound to method implementations at runtime • Dispatching handled by runtime environment • Simple messages take the form: • [object message]; • Can pass one or more arguments: • [object messageWithArg1:arg1 arg2:arg2]; Tuesday, August 10, 2010
  • 23. self and super • Methods have implicit reference to owning object called self (similar to Java’s this) • Additionally have access to superclass methods using super -(id)init { if (self = [super init]) { // do initialization } return self; } Tuesday, August 10, 2010
  • 24. Invoking methods in Java Map person = new HashMap(); person.put("name", "Joe Smith"); String address = "123 Street"; String house = address.substring(0, 3); person.put("houseNumber", house); List children = Arrays.asList("Sue", "Tom"); person.put("children", children); Tuesday, August 10, 2010
  • 25. Invoking methods in Objective-C NSMutableDictionary *person = [NSMutableDictionary dictionary]; [person setObject:@"Joe Smith" forKey:@"name"]; NSString *address = @"123 Street"; NSString *house = [address substringWithRange:NSMakeRange(0, 3)]; [person setObject:house forKey:@"houseNumber"]; NSArray *children = [NSArray arrayWithObjects:@"Sue", @"Tom", nil]; [person setObject:children forKey:@"children"]; Tuesday, August 10, 2010
  • 27. Memory Management Dude, where’s my Garbage Collection? • Garbage collection available for Mac apps (10.5+) • Use it if targeting 10.5+! • Use explicit memory management if targeting <= 10.4 • No garbage collection on iOS due to performance concerns. • Memory managed using simple reference counting mechanism: • Higher level abstraction than malloc / free • Straightforward approach, but must adhere to conventions and rules Tuesday, August 10, 2010
  • 28. Memory Management Reference Counting • Objective-C objects are reference counted • Objects start with reference count of 1 • Increased with retain • Decreased with release, autorelease • When count equals 0, runtime invokes dealloc 1 2 1 0 alloc retain release release Tuesday, August 10, 2010
  • 29. Memory Management Understanding the rules • Implicitly retain any object you create using: Methods starting with "alloc", "new", or contains "copy" e.g alloc, allocWithZone, newObject, mutableCopy,etc. • If you've retained it, you must release it • Many objects provide convenience methods that return an autoreleased reference. • Holding object reference from these methods does not make you the retainer • However, if you retain it you need an offsetting release or autorelease to free it Tuesday, August 10, 2010
  • 30. retain / release / autorelease @implementation BankAccount - (NSString *)accountNumber { return [[accountNumber retain] autorelease]; } - (void)setAccountNumber:(NSString *)newNumber { if (accountNumber != newNumber) { [accountNumber release]; accountNumber = [newNumber retain]; } } - (void)dealloc { [self setAccountNumber:nil]; [super dealloc]; } @end Tuesday, August 10, 2010
  • 32. Properties Simplifying Accessors • Object-C 2.0 introduced new syntax for defining accessor code • Much less verbose, less error prone • Highly configurable • Automatically generates accessor code • Compliments existing conventions and technologies • Key-Value Coding (KVC) • Key-Value Observing (KVO) • Cocoa Bindings • Core Data Tuesday, August 10, 2010
  • 33. Properties: Interface @property(attributes) type variable; Attribute Impacts readonly/readwrite Mutability assign/retain/copy Storage nonatomic Concurrency setter/getter API Tuesday, August 10, 2010
  • 34. Properties: Interface @property(attributes) type variable; Attribute Impacts readonly/readwrite Mutability assign/retain/copy Storage nonatomic Concurrency setter/getter API @property(readonly) NSString *acctNumber; Tuesday, August 10, 2010
  • 35. Properties: Interface @property(attributes) type variable; Attribute Impacts readonly/readwrite Mutability assign/retain/copy Storage nonatomic Concurrency setter/getter API @property(readwrite, copy) NSString *acctNumber; Tuesday, August 10, 2010
  • 36. Properties: Interface @property(attributes) type variable; Attribute Impacts readonly/readwrite Mutability assign/retain/copy Storage nonatomic Concurrency setter/getter API @property(nonatomic, retain) NSDate *activeOn; Tuesday, August 10, 2010
  • 37. Properties: Interface @property(attributes) type variable; Attribute Impacts readonly/readwrite Mutability assign/retain/copy Storage nonatomic Concurrency setter/getter API @property(readonly, getter=username) NSString *name; Tuesday, August 10, 2010
  • 38. Properties: Interface @interface BankAccount : NSObject { NSString *accountNumber; NSDecimalNumber *balance; NSDecimalNumber *fees; BOOL accountCurrent; } @property(readwrite, copy) NSString *accountNumber; @property(readwrite, retain) NSDecimalNumber *balance; @property(readonly) NSDecimalNumber *fees; @property(getter=isCurrent) BOOL accountCurrent; @end Tuesday, August 10, 2010
  • 39. Properties: Interface New in 10.6 @interface BankAccount : NSObject { and iOS 4 // Look ma, no more ivars } @property(readwrite, copy) NSString *accountNumber; @property(readwrite, retain) NSDecimalNumber *balance; @property(readonly) NSDecimalNumber *fees; @property(getter=isCurrent) BOOL accountCurrent; @end Tuesday, August 10, 2010
  • 40. Properties: Implementation @implementation BankAccount @synthesize accountNumber; @synthesize balance; @synthesize fees; @synthesize accountCurrent; ... @end Tuesday, August 10, 2010
  • 41. Properties: Implementation @implementation BankAccount New in 10.6 and iOS 4 // no more @synthesize statements ... @end Tuesday, August 10, 2010
  • 42. Accessing Properties • Generated properties are standard methods • Accessed through normal messaging syntax [object property]; [object setProperty:(id)newValue]; • Objective-C 2.0 property access via dot syntax object.property; object.property = newValue; Dot notation is just syntactic sugar. Still uses accessor methods. Doesn't get/set values directly. Tuesday, August 10, 2010
  • 44. Protocols Java’s Interface done Objective-C style • List of method declarations • Not associated with a particular class • Conformance, not class, is important • Useful in defining: • Methods that others are expected to implement • Declaring an interface while hiding its particular class • Capturing similarities among classes that aren't hierarchically related Tuesday, August 10, 2010
  • 45. Protocols NSCoding NSObject NSCoding Person Account CheckingAccount SavingAccount Tuesday, August 10, 2010
  • 46. Defining a Protocol NSCoding from Foundation Framework Objective-C equivalent to java.io.Externalizable @protocol NSCoding - (void)encodeWithCoder:(NSCoder *)aCoder; - (id)initWithCoder:(NSCoder *)aDecoder; @end Tuesday, August 10, 2010
  • 47. Adopting a Protocol @interface Person : NSObject <NSCoding> { NSString *name; NSString *street; NSString *city, *state, *zip; } // method declarations @end Tuesday, August 10, 2010
  • 48. Conforming to a Protocol Partial implementation of conforming Person class @implementation Person -(id)initWithCoder:(NSCoder *)coder { if (self = [super init]) { name = [coder decodeObjectForKey:@"name"]; [name retain]; } return self; } -(void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:name forKey:@"name"]; } @end Tuesday, August 10, 2010
  • 49. @required and @optional • Protocols methods are required by default • Can be relaxed with @optional directive @protocol SomeProtocol - (void)requiredMethod; @optional - (void)anOptionalMethod; - (void)anotherOptionalMethod; @required - (void)anotherRequiredMethod; @end Tuesday, August 10, 2010
  • 51. Categories Extending Object Features • Add new methods to existing classes • Alternative to subclassing • Defines new methods and can override existing • Does not define new instance variables • Becomes part of the class definition • Inherited by subclasses • Can be used as organizational tool • Often used in defining "private" methods Tuesday, August 10, 2010
  • 52. Using Categories Interface @interface NSString (Extensions) -(NSString *)trim; @end Implementation @implementation NSString (Extensions) -(NSString *)trim { NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet]; return [self stringByTrimmingCharactersInSet:charSet]; } @end Usage NSString *string = @" A string to be trimmed "; NSLog(@"Trimmed string: '%@'", [string trim]); Tuesday, August 10, 2010
  • 53. Class Extensions Unnamed Categories • Objective-C 2.0 adds ability to define "anonymous" categories • Category is unnamed • Treated as class interface continuations • Useful for implementing required "private" API • Compiler enforces methods are implemented Tuesday, August 10, 2010
  • 54. Class Extensions Example @interface Person : NSObject { NSString *name; } -(NSString *)name; @end Tuesday, August 10, 2010
  • 55. Class Extensions Example @interface Person () -(void)setName:(NSString *)newName; @end @implementation Person - (NSString *)name { return name; } - (void)setName:(NSString *)newName { name = newName; } @end Tuesday, August 10, 2010
  • 57. Objective-C Summary • Fully C, Fully Object-Oriented • Powerful dynamic runtime • Objective-C 2.0 added many useful new features • Garbage Collection for Mac OS X apps • Properties, Improved Categories & Protocols • Objective-C 2.1 continues its evolution: • Blocks (Closures) • Synthesize by default for properties Tuesday, August 10, 2010