Working with Cocoa and Objective-C

37
Working with Cocoa / Objective-C

description

Swift Tutorial Presentation

Transcript of Working with Cocoa and Objective-C

Page 1: Working with Cocoa and Objective-C

Working with Cocoa / Objective-C

Page 2: Working with Cocoa and Objective-C

Table of Contents

• Swift Import Process

• Interacting with Objective-C APIs

• Integrating with Interface Builder and more…

Page 3: Working with Cocoa and Objective-C

Swift Import Process

Page 4: Working with Cocoa and Objective-C

Importing Objective-C frameworks

• Any Objective-C framework can be imported directly into Swift*like Foundation, UIKit and common C Libraries

!import Foundation import UIKit

Page 5: Working with Cocoa and Objective-C

Import Process

• Objective-C header files are compiled to modules, which are imported as Swift APIs

• Type Remapping:

• id → AnyObject

• NSString → String …

Page 6: Working with Cocoa and Objective-C

Interacting with Objective-C APIs

Page 7: Working with Cocoa and Objective-C

Initialization

Page 8: Working with Cocoa and Objective-C

Initializers• No alloc in Swift!

!// Objective-C UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped]; !// Swift let myTableView = UITableView(frame: CGRectZero, style: .Grouped)

Page 9: Working with Cocoa and Objective-C

Factory Methods• Objective-C factory methods get mapped to

convenience initialisers in Swift

!// Objective-C UIColor *color = [UIColor colorWithRed:0.5 green:0.0 blue:0.5 alpha:1.0]; !// Swift let color = UIColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 1.0)

Page 10: Working with Cocoa and Objective-C

Accessing Properties

Page 11: Working with Cocoa and Objective-C

Accessing Properties• Use dot syntax

!let str: NSString = "hoge" // get let count = str.length !let label = UILabel() // set label.text = str

Page 12: Working with Cocoa and Objective-C

Methods

Page 13: Working with Cocoa and Objective-C

Methods• Use dot syntax

!// Objective-C [myTableView insertSubview:mySubview atIndex:2]; !!// Swift myTableView.insertSubview(mySubview, atIndex: 2)

• () are needed even when a method doesn’t have any arguments!myTableView.layoutIfNeeded()

Page 14: Working with Cocoa and Objective-C

id

Page 15: Working with Cocoa and Objective-C

AnyObject• AnyObject is id in Swift.

• Swift imports id as AnyObject

!// Any class type can be assigned. var myObj: AnyObject = UITableView() !// a different type object can be assigned. myObj = UIView()

Page 16: Working with Cocoa and Objective-C

Unsafe Code• The specific type of AnyObject isn’t known

until runtime…

!var myObj: AnyObject = UITableView() !// Crash // because UITableView cannot respond to "length()" myObj.length()

Page 17: Working with Cocoa and Objective-C

Optionals!• The following method calls behave like implicitly

unwrapped optionals when calling an Objective-C method.!var myObj: AnyObject = NSDate() !// These method are never executed. let count = myObj.count? let myChar = myObj.characterAtIndex?(5) !if let frame = myObj.frame { println("frame: \(frame)") }

Page 18: Working with Cocoa and Objective-C

Downcasting• Casting from AnyObject to a more specific

object type returns an optional value. !let userDefaults = NSUserDefaults.standardUserDefaults() let lastDate: AnyObject? = userDefaults.objectForKey("LastDate") !// This downcasting is not guaranteed to succeed. if let date = lastDate as? NSDate { println("\(date.timeIntervalSinceReferenceDate)") } !// if 100% sure to succeed, “as” can be used! let date = lastDate as NSDate let timeInterval = date.timeIntervalSinceReferenceDate

Page 19: Working with Cocoa and Objective-C

nil

Page 20: Working with Cocoa and Objective-C

Working with nil• When importing Objective-C APIs,

all classes in arguments and return types are converted to implicitly unwrapped optional!

• Should check and unwrap an implicitly unwrapped optional object

var view: UIView! = UIView() view = nil !// crash! //println("\(view.frame)") !// SHOULD check whether view is nil or not if view != nil { println("\(view.frame)") } else { println("view is nil...") }

Page 21: Working with Cocoa and Objective-C

Blocks

Page 22: Working with Cocoa and Objective-C

Blocks• “Swift Closures” and “Objective-C Blocks” are

compatible

• Objective-C blocks are converted to Swift Closures

!// Objective-C void (^completionBlock)(NSData *, NSError *) = ^(NSData *data, NSError *error) {/* ... */} !// Swift let completionBlock: (NSData, NSError) -> Void = {data, error in /* ... */}

Page 23: Working with Cocoa and Objective-C

Capture Semantics

• Basically, Closures have similar semantics as Blocks

• Difference:

• Variables are mutable rather than copied

• __block in Objective-C is default behavior

Page 24: Working with Cocoa and Objective-C

Swift Type Compatibility

Page 25: Working with Cocoa and Objective-C

@objc attribute• When a Swift class inherits from NSObject, the class automatically

compatibele with Objective-C.

• @objc attribute is needed to use from Objective-C if a Swift class doesn't inherit from NSObject.

• @objc attribute makes Swift APIs available in Objective-C

@objc(SomeClass) class SomeClass { var value: Int init(value: Int) { self.value = value } func printValue() { println("value is \(value)") } }

Page 26: Working with Cocoa and Objective-C

Swift APIs in Objective-C !// Swift init(songName: String, artist: String) !// Objective-C - (instancetype)initWithSongName:(NSString *)songName artist:(NSString *)artist; !!// Swift func playSong(name: String) !// Objective-C - (void)playSong:(NSString *)name;

Page 27: Working with Cocoa and Objective-C

Objective-C Selectors

Page 28: Working with Cocoa and Objective-C

Selector in Swift• A Objective-C selector is a type that refers to an

Objective-C method

• Objective-C selectors are represented by Selector structure in Swift

!let mySelector: Selector = "tappedButton:"

Page 29: Working with Cocoa and Objective-C

Common Use Case!class MyViewController: UIViewController { let myButton = UIButton(frame:CGRect(x:0,y:0,width:50,height: 50)) override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) myButton.addTarget(self, action: "tappedButton:", forControlEvents: .TouchUpInside) } ! required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tappedButton(sender: UIButton!) { println("tapped button") } }

Page 30: Working with Cocoa and Objective-C

Integrating with Interface Builder

Page 31: Working with Cocoa and Objective-C

Outlets and Actions• @IBOutlet for Outlets, @IBAction for Actions

• The type of the outlet should be implicitly unwrapped optional.

!class MyViewController: UIViewController { @IBOutlet weak var button: UIButton! @IBAction func buttonTapped(AnyObject) { println("button tapped!") } }

Page 32: Working with Cocoa and Objective-C

Property Attributes

Page 33: Working with Cocoa and Objective-C

Strong and Weak

• Swift properties are strong by default

• weak keyword indicates that a property has a weak reference to the object

• This keyword can be used only for optional properties.

Page 34: Working with Cocoa and Objective-C

Read/Write and Read-Only

• Swift has no readwrite and readonly attributes

• let for readonly

• var for readwrite

Page 35: Working with Cocoa and Objective-C

Copy Semantics

• @NSCopying is copy property in Objective-C

• must conform to NSCopying protocol

Page 36: Working with Cocoa and Objective-C

Wrap Up• Looking through how to work with Cocoa /

Objective-C

• For more detail,Using Swift with Cocoa and Objective-C https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/

Page 37: Working with Cocoa and Objective-C

Thank you