SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
Working with Cocoa / Objective-C
Table of Contents
• Swift Import Process
• Interacting with Objective-C APIs
• Integrating with Interface Builder



and more…
Swift Import Process
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
Import Process
• Objective-C header files are compiled to
modules, which are imported as Swift APIs
• Type Remapping:
• id → AnyObject
• NSString → String …
Interacting with Objective-C
APIs
Initialization
Initializers
• No alloc in Swift!
!
// Objective-C
UITableView *myTableView = [[UITableView alloc]
initWithFrame:CGRectZero style:UITableViewStyleGrouped];
!
// Swift
let myTableView = UITableView(frame: CGRectZero, style: .Grouped)
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)
Accessing Properties
Accessing Properties
• Use dot syntax
!
let str: NSString = "hoge"
// get
let count = str.length
!
let label = UILabel()
// set
label.text = str
Methods
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()
id
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()
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()
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)")
}
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
nil
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...")
}
Blocks
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 /* ... */}
Capture Semantics
• Basically, Closures have similar semantics as
Blocks
• Difference:
• Variables are mutable rather than copied
• __block in Objective-C is default behavior
Swift Type Compatibility
@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)")
}
}
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;
Objective-C Selectors
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:"
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")
}
}
Integrating with 

Interface Builder
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!")
}
}
Property Attributes
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.
Read/Write and Read-Only
• Swift has no readwrite and readonly attributes
• let for readonly
• var for readwrite
Copy Semantics
• @NSCopying is copy property in Objective-C
• must conform to NSCopying protocol
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/
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
Yandex
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
Vasil Remeniuk
 

Was ist angesagt? (20)

Introduction to Swift 2
Introduction to Swift 2Introduction to Swift 2
Introduction to Swift 2
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Swift Basics
Swift BasicsSwift Basics
Swift Basics
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
SWIFT 3
SWIFT 3SWIFT 3
SWIFT 3
 
Swift - the future of iOS app development
Swift - the future of iOS app developmentSwift - the future of iOS app development
Swift - the future of iOS app development
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Swift 2
Swift 2Swift 2
Swift 2
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP Language
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 

Ähnlich wie Working with Cocoa and Objective-C

FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
Petr Dvorak
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS Topics
Petr Dvorak
 

Ähnlich wie Working with Cocoa and Objective-C (20)

Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법
 
iOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIsiOS 101 - Xcode, Objective-C, iOS APIs
iOS 101 - Xcode, Objective-C, iOS APIs
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Cappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkCappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application Framework
 
Pioc
PiocPioc
Pioc
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to Swift
 
Live Updating Swift Code
Live Updating Swift CodeLive Updating Swift Code
Live Updating Swift Code
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overview
 
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
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
Swift for-rubyists
Swift for-rubyistsSwift for-rubyists
Swift for-rubyists
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
Day 1
Day 1Day 1
Day 1
 
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
Conceitos e prática no desenvolvimento iOS - Mobile Conf 2014
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS Topics
 
The Dark Side of Objective-C
The Dark Side of Objective-CThe Dark Side of Objective-C
The Dark Side of Objective-C
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 

Working with Cocoa and Objective-C

  • 1. Working with Cocoa / Objective-C
  • 2. Table of Contents • Swift Import Process • Interacting with Objective-C APIs • Integrating with Interface Builder
 
 and more…
  • 4. 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
  • 5. Import Process • Objective-C header files are compiled to modules, which are imported as Swift APIs • Type Remapping: • id → AnyObject • NSString → String …
  • 8. Initializers • No alloc in Swift! ! // Objective-C UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped]; ! // Swift let myTableView = UITableView(frame: CGRectZero, style: .Grouped)
  • 9. 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)
  • 11. Accessing Properties • Use dot syntax ! let str: NSString = "hoge" // get let count = str.length ! let label = UILabel() // set label.text = str
  • 13. 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()
  • 14. id
  • 15. 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()
  • 16. 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()
  • 17. 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)") }
  • 18. 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
  • 19. nil
  • 20. 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...") }
  • 22. 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 /* ... */}
  • 23. Capture Semantics • Basically, Closures have similar semantics as Blocks • Difference: • Variables are mutable rather than copied • __block in Objective-C is default behavior
  • 25. @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)") } }
  • 26. 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;
  • 28. 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:"
  • 29. 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") } }
  • 31. 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!") } }
  • 33. 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.
  • 34. Read/Write and Read-Only • Swift has no readwrite and readonly attributes • let for readonly • var for readwrite
  • 35. Copy Semantics • @NSCopying is copy property in Objective-C • must conform to NSCopying protocol
  • 36. 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/