SlideShare a Scribd company logo
1 of 46
Objective-C Is Not Java
  Chris Adamson • @invalidname
         CodeMash 2013
What This Is


• A guide to writing idiomatic Obj-C code
  • Easier to write
  • Easier to maintain
• Based on current real-world conventions
What This Is Not



• An advocacy piece for Objective-C
• A slam on your favorite language
Scope
• Covering Objective-C as used in OS X / iOS
 SDKs

  • Obj-C is effectively owned by Apple
  • Language versions are now tied to releases of
    Xcode

• We are not concerned with Obj-C use outside
 of Apple ecosystem, nor advocating it

• No history lesson today
Start with a Demo
Classes and Objects

• There is no root class, just the C pointer id   



typedef struct objc_class *Class;
typedef struct objc_object {
    Class isa;
} *id;

• Can call any method on id
• That said, effectively everything in the SDK
 subclasses NSObject
Methods / messages
• Call a method on an object with []
  •[foo bar];
  •[foo bar: 1 withBaz: 2];
• Method calls are really message dispatches
• OK for foo to be nil. Not OK if foo’s class
 doesn’t understand bar or bar:withBaz:

  • 🙅 Don’t check variables for nil.
New objects
• alloc allocates memory for a new object, init
      sets up its state. Always do both.

 
NSMutableArray *mutableSessions =


 
 
 [[NSMutableArray alloc] init];


      • [Class new] is equivalent to [[Class
        alloc] init]. 🙅 Nobody uses it.

• Some classes have convenience initializers:
      [NSURL URLWithString:] instead of
      [[NSURL alloc] initWithString:]
Initializers

• Some classes have many initializers for
  different purposes

  • NSString — initWithData:encoding:,
    initWithUTF8String:, etc.

• Designated initializer — the initializer that sets
  the most state; other initializers can call this
  with default values
End-of-life

• dealloc is called when an object is being
 destroyed. Override for needed cleanup, end
 with [super dealloc]

  • 🙆 Can actually count on this, unlike Java’s
    finalize()

• Not as big a deal as it used to be (see ARC,
 later)
Class files
• Typically, you create two files
  • Header (.h) for anything pubic. Contains the
    Obj-C @interface directive

  • Implementation (usually .m) for anything
    private. Contains @implementation.

  • 🙍 No equivalent of Java protected (i.e.,
    only accessible by subclasses) or C++
    friendly
Importing headers
• C’s #include copies all of a file (usually a .h)
 into a compile. Obj-C’s #import is similar, but
 avoids copying same file twice.

  • 🙆 Always prefer #import in Obj-C code
• “Class.h” looks in current directory,
 <Framework/Class.h> searches paths.

• @class is a forward declaration, used to break
 circular dependencies in headers
Namespaces

• Objective-C does not have namespaces. 🙍
• Accepted practice is class naming convention:
  • Apple prefixes classes with 2 uppercase
    letters (NS, UI, CA, SK, AV, etc.)

  • Your classes should use a 3-letter prefix
  • Xcode project creation now prompts for this
CMHSession.h
#import <Foundation/Foundation.h>

@interface CMHSession : NSObject

@property (copy) NSString *speakerName;
@property (copy) NSString *title;
@property (copy) NSString *abstract;
@property (copy) NSString *room;
@property (strong) NSDate *start;
@property (copy) NSString *technology;
@property (copy) NSURL *url;

@property (copy) NSString *userComments;
@property (assign) NSInteger *userScore;

-(id) initWithJSONDictionary: (NSDictionary*) dict;

@end
@implementation

• Method implementations go here, in .m file
  • Public methods (from .h) and private
  • Private methods used to have to be in order
    you called them (caveat on next slide), but
    that doesn’t matter with LLVM multi-pass
    compile
Class Extension

• Like a second @interface, but in the .m file
 (and therefore only visible within that file)

• Obj-C’s equivalent to the C forward
 declaration

  • Not visible to subclasses 🙍
• Mostly used now for private properties (see
 later slide)
Class Extension

@interface CMHSessionNotesViewController ()
- (IBAction)handleDoneTapped:(id)sender;
@property (weak, nonatomic) IBOutlet UITextView *notesView;

@end

@implementation CMHSessionNotesViewController
- (IBAction)handleDoneTapped:(id)sender {
// method implementation goes here
}
@end



Note: The @interface mus! be named ClassName()
Categories

• Allow you to add methods to classes you don’t
 own (including Apple’s!)

  • Cannot add state (instance variables,
    properties)

• Often added to NSString, collections
• By convention, file name is ClassName
 +CategoryName
NSArray+BoundsChecking.h


  #import <Foundation/Foundation.h>
  
  @interface NSArray (BoundsChecking)
  -(id) firstObject;
  @end
NSArray+BoundsChecking.m

 #import "NSArray+BoundsChecking.h"
 
 @implementation NSArray (BoundsChecking)
 -(id) firstObject {
 
 if ([self count] == 0) {
 
 
 return nil;
 
 }
 
 return [self objectAtIndex:0];
 }
 @end
Protocols


   • List of methods, similar to Java interface
   • Group methods together under the
     @required and @optional directives.

   • Classes declare their implementation of
     protocol with <> after declaring subclass

@interface CMHSessionListViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate>
Memory Management

• Obj-C uses reference counting, not garbage
 collection 🙅

• Any object you create (alloc, copy) must
 eventually be release’d.

  • To keep an object around, call retain, then
    release when done.

• This mostly doesn’t matter anymore, because…
Automatic Reference
          Counting
• LLVM understands the retain/release rules,
 and applies them for you. You no longer write
 retain/release.

  • It’s still not GC. Objects freed immediately
    when reference count equals zero

• Can be enabled at the project or file level
• 🙆 Everyone’s using it now.
Properties

• An instance variable combined with getter/
 setter methods, all built for you by the
 compiler.

• Declaration also specifies threading, memory
 management, and writability

• Accessed via the dot operator, not brackets

 self.speakerName = [dict valueForKey:@"SpeakerName"];

 

 cell.speakerLabel.text = session.speakerName;
Property attributes
• readonly / readwrite
• nonatomic — Concurrent access OK. Used
 for UIKit (which should only ever be called
 from main thread)

• strong / weak — Whether this object retains
 the property, thereby keeping it from being
 freed

  • Also assign (for primitives), copy
Property naming

• For property foo, synthesized ivar is _foo,
 getter is foo, setter is setFoo:

  • @synthesize directive lets you specify/
    rename property variable or methods.

  • 🙅 Never use get in a method name
• 💁 For BOOLs, use adjectiv" or #erbsNou$
 style, e.g., editable or allowsEditing
Other Naming Conventions
• Method names should imply their argument
  • What does [sort: YES] mean? 
     • How about [sort: @”name”] ?
  • Aren’t these better as [sortAscending:
    YES] , [sortByProperty:@”name”] ?

• Callbacks often start with who’s calling:
 tableView:didSelectRowAtIndexPath:
Grand Central Dispatch

• Threads are good on multi-core, but how many
 threads are ideal?

  • The OS is in the best position to know, so
    let it decide

  • Organize work into discrete blocks, give it to
    the system and let it figure out how to run it
Blocks
• Closures for C, or function pointers that
 capture their enclosing scope

  • Start with ^ character, then return types,
    parameter list, and code in {…}.

  • Commonly used as “completion handlers”
    for long-running operations (network,
    media, etc.)

  • Example to follow…
UIKit Threading

• All access to UIKit must be on the main
 thread (sound like AWT/Swing, anyone?)

  • UI events will come from this thread.
    Network callbacks often won’t.

• Long-running tasks must not be on main
 thread, or they’ll block the UI (sound like
 AWT/Swing, anyone?) 🙍
GCD Recipes

• Put work on other threads with C function
 dispatch_async(), which takes a GCD
 queue and a block to execute

  • To get off main thread, get queue with
    dispatch_get_global_queue()

  • To get o$ main thread, use
    dispatch_get_main_queue()
Off main queue and back on

dispatch_async(dispatch_get_global_queue

 
 
    
 
 
 
 (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),

 
 
 
 
 
 
 ^{

 // perform long-running task

 dispatch_async(dispatch_get_main_queue(), ^{

 // update the ui

 });
});
Speaking of C




 Available on iBooks
Apple still loves C
• Utility routines that don’t need to be tied to a class are
 often C functions: e.g, NSLog()

• High-performance frameworks are in C
• Constants may be enums in a typedef       




enum {


 NSOrderedAscending = -1,


 NSOrderedSame,


 NSOrderedDescending

};

typedef NSInteger NSComparisonResult;
All objects are pointers
      • All Obj-C object declarations take *, because
        they’re pointers

        • Except for type id, which is already a pointer
      • ** means “pointer to object”, used when
        populating as a side effect

NSError *jsonErr = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 options:0

 
 
 
 
 
 
 
 
 
 
 
 
 
          
 
 
 
 
 error:&jsonErr];
A Slide on Frameworks

• Apple’s stuff is packaged as “frameworks” (not
 “libraries”), in .framework bundles

  • Framework = executable library + headers +
    documentation + resources (graphics, sound,
    localizations, etc.)

• The bigs: UIKit, Foundation
• Not easy to create your own with Xcode
Apple’s Favorite Patterns

• MVC (you all know this 🙆)
• Target-Action
• Key-Value Coding
• Delegation
• Completion Handler
Target-Action

• Indicates how an event (like a button tap) is to
 be handled. Sender is provided with:

  • Action: a method signature as a @selector
  • Target: object to call the method on
• Method signature must be known in advance.
 UIKit most commonly uses

 -(IBAction) action:(id) sender
Key-Value Coding
• Allows access into nested object structures as a
 dot-separated string (e.g., “user.name” in a
 tweet returned by Twitter API)

  • Each key segment is fetched by
    valueForKey:, which looks for property or
    ivar of that name (or could be overridden)

• Used for sorting collections, also with “magic”
 key path members (“@avg.value”,
 “@min.date”)
Delegation
• Common means of extending a class’
 functionality, by making defined callbacks to
 one object that you write.

  • Methods usually collected in a protocol
  • You declare that your object implements the
    protocol, then set it as the delegate
    property of the other class

• 🙅 We don’t subclass much in iOS. This is why.
Completion Handler

• A block to be completed when a long-running
 task (animation, network access) completes.

  • Parameters to the block may provide results
    of the task

  • For anything else you need, remember that
    everything in scope prior to the block’s
    creation is available inside the block
A look inside our demo
Modern Obj-C habits

• Only use .h for public stuff
  • All private stuff (properties, methods) can
    now go in a class extension in the .m

• Prefer private properties to instance variables
• Get off the main thread; blocks are cheap
Old Habits Die Hard
• Obj-C literals in Xcode 4.4
• Arrays: @[…] instead of [NSArray
 arrayWithObjects:…]

• Dictionaries @{ name1:value1,
 name2:value2, …} instead of
 [NSDictionary
 dictionaryWithValuesAndKeys:…]

• Accessors: array[i], dict[“key”]
Final Thoughts

• Obj-C / Cocoa have consistent idioms you’ll see
 in Apple’s frameworks.

  • Adopt them, emulate them, don’t fight them
• Like any language, Obj-C has its share of good
 and bad.

  • Unfamiliar != bad
Learn More!




Available on iBooks   Available at pragprog.com

More Related Content

What's hot

Squeak DBX
Squeak DBXSqueak DBX
Squeak DBXESUG
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORPESUG
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than YouRobert Cooper
 
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014Robert Stupp
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?Roman Elizarov
 
Lagergren jvmls-2013-final
Lagergren jvmls-2013-finalLagergren jvmls-2013-final
Lagergren jvmls-2013-finalMarcus Lagergren
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoTaro L. Saito
 
The Return of the Living Datalog
The Return of the Living DatalogThe Return of the Living Datalog
The Return of the Living DatalogMike Fogus
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Sunghyouk Bae
 
The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018Charles Nutter
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touchmobiledeveloperpl
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 

What's hot (20)

Squeak DBX
Squeak DBXSqueak DBX
Squeak DBX
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORP
 
GWT is Smarter Than You
GWT is Smarter Than YouGWT is Smarter Than You
GWT is Smarter Than You
 
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?
 
Lagergren jvmls-2013-final
Lagergren jvmls-2013-finalLagergren jvmls-2013-final
Lagergren jvmls-2013-final
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
 
The Return of the Living Datalog
The Return of the Living DatalogThe Return of the Living Datalog
The Return of the Living Datalog
 
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018Kotlin @ Coupang Backed - JetBrains Day seoul 2018
Kotlin @ Coupang Backed - JetBrains Day seoul 2018
 
The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018
 
Threading in iOS / Cocoa Touch
Threading in iOS / Cocoa TouchThreading in iOS / Cocoa Touch
Threading in iOS / Cocoa Touch
 
Rails Performance
Rails PerformanceRails Performance
Rails Performance
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 

Similar to Objective-C Is Not Java

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 for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical StuffPetr Dvorak
 
Java Course — Mastering the Fundamentals
Java Course — Mastering the FundamentalsJava Course — Mastering the Fundamentals
Java Course — Mastering the Fundamentalsnehash4637
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
iPhone dev intro
iPhone dev introiPhone dev intro
iPhone dev introVonbo
 
Beginning to iPhone development
Beginning to iPhone developmentBeginning to iPhone development
Beginning to iPhone developmentVonbo
 
Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CDataArt
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
Objective-C talk
Objective-C talkObjective-C talk
Objective-C talkbradringel
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 

Similar to Objective-C Is Not Java (20)

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 for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
 
Java Course — Mastering the Fundamentals
Java Course — Mastering the FundamentalsJava Course — Mastering the Fundamentals
Java Course — Mastering the Fundamentals
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
iPhone dev intro
iPhone dev introiPhone dev intro
iPhone dev intro
 
Beginning to iPhone development
Beginning to iPhone developmentBeginning to iPhone development
Beginning to iPhone development
 
Никита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-CНикита Корчагин - Programming Apple iOS with Objective-C
Никита Корчагин - Programming Apple iOS with Objective-C
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
Objective-C talk
Objective-C talkObjective-C talk
Objective-C talk
 
java01.pdf
java01.pdfjava01.pdf
java01.pdf
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
RIBBUN SOFTWARE
RIBBUN SOFTWARERIBBUN SOFTWARE
RIBBUN SOFTWARE
 
Java01
Java01Java01
Java01
 
Java01
Java01Java01
Java01
 
Java01
Java01Java01
Java01
 
Java01
Java01Java01
Java01
 
Introduction what is java
Introduction what is javaIntroduction what is java
Introduction what is java
 

More from Chris Adamson

Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)Chris Adamson
 
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)Chris Adamson
 
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)Chris Adamson
 
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...Chris Adamson
 
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineCocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineChris Adamson
 
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineForward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineChris Adamson
 
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...Chris Adamson
 
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)Chris Adamson
 
Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)Chris Adamson
 
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)Chris Adamson
 
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)Chris Adamson
 
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)Chris Adamson
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Chris Adamson
 
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014Chris Adamson
 
Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Chris Adamson
 
Stupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasStupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasChris Adamson
 
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Chris Adamson
 
Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)Chris Adamson
 
Introduction to the Roku SDK
Introduction to the Roku SDKIntroduction to the Roku SDK
Introduction to the Roku SDKChris Adamson
 

More from Chris Adamson (20)

Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
 
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
 
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
 
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
 
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is FineCocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
 
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is FineForward Swift 2017: Media Frameworks and Swift: This Is Fine
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
 
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
 
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
 
Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)Firebase: Totally Not Parse All Over Again (Unless It Is)
Firebase: Totally Not Parse All Over Again (Unless It Is)
 
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
 
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
 
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
 
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
 
Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014Stupid Video Tricks, CocoaConf Seattle 2014
Stupid Video Tricks, CocoaConf Seattle 2014
 
Stupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las VegasStupid Video Tricks, CocoaConf Las Vegas
Stupid Video Tricks, CocoaConf Las Vegas
 
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
 
Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)Stupid Video Tricks (CocoaConf DC, March 2014)
Stupid Video Tricks (CocoaConf DC, March 2014)
 
Stupid Video Tricks
Stupid Video TricksStupid Video Tricks
Stupid Video Tricks
 
Introduction to the Roku SDK
Introduction to the Roku SDKIntroduction to the Roku SDK
Introduction to the Roku SDK
 

Recently uploaded

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
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
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 

Recently uploaded (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
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
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 

Objective-C Is Not Java

  • 1. Objective-C Is Not Java Chris Adamson • @invalidname CodeMash 2013
  • 2. What This Is • A guide to writing idiomatic Obj-C code • Easier to write • Easier to maintain • Based on current real-world conventions
  • 3. What This Is Not • An advocacy piece for Objective-C • A slam on your favorite language
  • 4. Scope • Covering Objective-C as used in OS X / iOS SDKs • Obj-C is effectively owned by Apple • Language versions are now tied to releases of Xcode • We are not concerned with Obj-C use outside of Apple ecosystem, nor advocating it • No history lesson today
  • 6. Classes and Objects • There is no root class, just the C pointer id typedef struct objc_class *Class; typedef struct objc_object { Class isa; } *id; • Can call any method on id • That said, effectively everything in the SDK subclasses NSObject
  • 7. Methods / messages • Call a method on an object with [] •[foo bar]; •[foo bar: 1 withBaz: 2]; • Method calls are really message dispatches • OK for foo to be nil. Not OK if foo’s class doesn’t understand bar or bar:withBaz: • 🙅 Don’t check variables for nil.
  • 8. New objects • alloc allocates memory for a new object, init sets up its state. Always do both. NSMutableArray *mutableSessions = [[NSMutableArray alloc] init]; • [Class new] is equivalent to [[Class alloc] init]. 🙅 Nobody uses it. • Some classes have convenience initializers: [NSURL URLWithString:] instead of [[NSURL alloc] initWithString:]
  • 9. Initializers • Some classes have many initializers for different purposes • NSString — initWithData:encoding:, initWithUTF8String:, etc. • Designated initializer — the initializer that sets the most state; other initializers can call this with default values
  • 10. End-of-life • dealloc is called when an object is being destroyed. Override for needed cleanup, end with [super dealloc] • 🙆 Can actually count on this, unlike Java’s finalize() • Not as big a deal as it used to be (see ARC, later)
  • 11. Class files • Typically, you create two files • Header (.h) for anything pubic. Contains the Obj-C @interface directive • Implementation (usually .m) for anything private. Contains @implementation. • 🙍 No equivalent of Java protected (i.e., only accessible by subclasses) or C++ friendly
  • 12. Importing headers • C’s #include copies all of a file (usually a .h) into a compile. Obj-C’s #import is similar, but avoids copying same file twice. • 🙆 Always prefer #import in Obj-C code • “Class.h” looks in current directory, <Framework/Class.h> searches paths. • @class is a forward declaration, used to break circular dependencies in headers
  • 13. Namespaces • Objective-C does not have namespaces. 🙍 • Accepted practice is class naming convention: • Apple prefixes classes with 2 uppercase letters (NS, UI, CA, SK, AV, etc.) • Your classes should use a 3-letter prefix • Xcode project creation now prompts for this
  • 14. CMHSession.h #import <Foundation/Foundation.h> @interface CMHSession : NSObject @property (copy) NSString *speakerName; @property (copy) NSString *title; @property (copy) NSString *abstract; @property (copy) NSString *room; @property (strong) NSDate *start; @property (copy) NSString *technology; @property (copy) NSURL *url; @property (copy) NSString *userComments; @property (assign) NSInteger *userScore; -(id) initWithJSONDictionary: (NSDictionary*) dict; @end
  • 15. @implementation • Method implementations go here, in .m file • Public methods (from .h) and private • Private methods used to have to be in order you called them (caveat on next slide), but that doesn’t matter with LLVM multi-pass compile
  • 16. Class Extension • Like a second @interface, but in the .m file (and therefore only visible within that file) • Obj-C’s equivalent to the C forward declaration • Not visible to subclasses 🙍 • Mostly used now for private properties (see later slide)
  • 17. Class Extension @interface CMHSessionNotesViewController () - (IBAction)handleDoneTapped:(id)sender; @property (weak, nonatomic) IBOutlet UITextView *notesView; @end @implementation CMHSessionNotesViewController - (IBAction)handleDoneTapped:(id)sender { // method implementation goes here } @end Note: The @interface mus! be named ClassName()
  • 18. Categories • Allow you to add methods to classes you don’t own (including Apple’s!) • Cannot add state (instance variables, properties) • Often added to NSString, collections • By convention, file name is ClassName +CategoryName
  • 19. NSArray+BoundsChecking.h #import <Foundation/Foundation.h> @interface NSArray (BoundsChecking) -(id) firstObject; @end
  • 20. NSArray+BoundsChecking.m #import "NSArray+BoundsChecking.h" @implementation NSArray (BoundsChecking) -(id) firstObject { if ([self count] == 0) { return nil; } return [self objectAtIndex:0]; } @end
  • 21. Protocols • List of methods, similar to Java interface • Group methods together under the @required and @optional directives. • Classes declare their implementation of protocol with <> after declaring subclass @interface CMHSessionListViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
  • 22. Memory Management • Obj-C uses reference counting, not garbage collection 🙅 • Any object you create (alloc, copy) must eventually be release’d. • To keep an object around, call retain, then release when done. • This mostly doesn’t matter anymore, because…
  • 23. Automatic Reference Counting • LLVM understands the retain/release rules, and applies them for you. You no longer write retain/release. • It’s still not GC. Objects freed immediately when reference count equals zero • Can be enabled at the project or file level • 🙆 Everyone’s using it now.
  • 24. Properties • An instance variable combined with getter/ setter methods, all built for you by the compiler. • Declaration also specifies threading, memory management, and writability • Accessed via the dot operator, not brackets
 self.speakerName = [dict valueForKey:@"SpeakerName"];
 
 cell.speakerLabel.text = session.speakerName;
  • 25. Property attributes • readonly / readwrite • nonatomic — Concurrent access OK. Used for UIKit (which should only ever be called from main thread) • strong / weak — Whether this object retains the property, thereby keeping it from being freed • Also assign (for primitives), copy
  • 26. Property naming • For property foo, synthesized ivar is _foo, getter is foo, setter is setFoo: • @synthesize directive lets you specify/ rename property variable or methods. • 🙅 Never use get in a method name • 💁 For BOOLs, use adjectiv" or #erbsNou$ style, e.g., editable or allowsEditing
  • 27. Other Naming Conventions • Method names should imply their argument • What does [sort: YES] mean? • How about [sort: @”name”] ? • Aren’t these better as [sortAscending: YES] , [sortByProperty:@”name”] ? • Callbacks often start with who’s calling: tableView:didSelectRowAtIndexPath:
  • 28. Grand Central Dispatch • Threads are good on multi-core, but how many threads are ideal? • The OS is in the best position to know, so let it decide • Organize work into discrete blocks, give it to the system and let it figure out how to run it
  • 29. Blocks • Closures for C, or function pointers that capture their enclosing scope • Start with ^ character, then return types, parameter list, and code in {…}. • Commonly used as “completion handlers” for long-running operations (network, media, etc.) • Example to follow…
  • 30. UIKit Threading • All access to UIKit must be on the main thread (sound like AWT/Swing, anyone?) • UI events will come from this thread. Network callbacks often won’t. • Long-running tasks must not be on main thread, or they’ll block the UI (sound like AWT/Swing, anyone?) 🙍
  • 31. GCD Recipes • Put work on other threads with C function dispatch_async(), which takes a GCD queue and a block to execute • To get off main thread, get queue with dispatch_get_global_queue() • To get o$ main thread, use dispatch_get_main_queue()
  • 32. Off main queue and back on dispatch_async(dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // perform long-running task dispatch_async(dispatch_get_main_queue(), ^{ // update the ui }); });
  • 33. Speaking of C Available on iBooks
  • 34. Apple still loves C • Utility routines that don’t need to be tied to a class are often C functions: e.g, NSLog() • High-performance frameworks are in C • Constants may be enums in a typedef enum { NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending }; typedef NSInteger NSComparisonResult;
  • 35. All objects are pointers • All Obj-C object declarations take *, because they’re pointers • Except for type id, which is already a pointer • ** means “pointer to object”, used when populating as a side effect NSError *jsonErr = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonErr];
  • 36. A Slide on Frameworks • Apple’s stuff is packaged as “frameworks” (not “libraries”), in .framework bundles • Framework = executable library + headers + documentation + resources (graphics, sound, localizations, etc.) • The bigs: UIKit, Foundation • Not easy to create your own with Xcode
  • 37. Apple’s Favorite Patterns • MVC (you all know this 🙆) • Target-Action • Key-Value Coding • Delegation • Completion Handler
  • 38. Target-Action • Indicates how an event (like a button tap) is to be handled. Sender is provided with: • Action: a method signature as a @selector • Target: object to call the method on • Method signature must be known in advance. UIKit most commonly uses
 -(IBAction) action:(id) sender
  • 39. Key-Value Coding • Allows access into nested object structures as a dot-separated string (e.g., “user.name” in a tweet returned by Twitter API) • Each key segment is fetched by valueForKey:, which looks for property or ivar of that name (or could be overridden) • Used for sorting collections, also with “magic” key path members (“@avg.value”, “@min.date”)
  • 40. Delegation • Common means of extending a class’ functionality, by making defined callbacks to one object that you write. • Methods usually collected in a protocol • You declare that your object implements the protocol, then set it as the delegate property of the other class • 🙅 We don’t subclass much in iOS. This is why.
  • 41. Completion Handler • A block to be completed when a long-running task (animation, network access) completes. • Parameters to the block may provide results of the task • For anything else you need, remember that everything in scope prior to the block’s creation is available inside the block
  • 42. A look inside our demo
  • 43. Modern Obj-C habits • Only use .h for public stuff • All private stuff (properties, methods) can now go in a class extension in the .m • Prefer private properties to instance variables • Get off the main thread; blocks are cheap
  • 44. Old Habits Die Hard • Obj-C literals in Xcode 4.4 • Arrays: @[…] instead of [NSArray arrayWithObjects:…] • Dictionaries @{ name1:value1, name2:value2, …} instead of [NSDictionary dictionaryWithValuesAndKeys:…] • Accessors: array[i], dict[“key”]
  • 45. Final Thoughts • Obj-C / Cocoa have consistent idioms you’ll see in Apple’s frameworks. • Adopt them, emulate them, don’t fight them • Like any language, Obj-C has its share of good and bad. • Unfamiliar != bad
  • 46. Learn More! Available on iBooks Available at pragprog.com