SlideShare a Scribd company logo
1 of 37
Download to read offline
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

More Related Content

What's hot

Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
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?Nikita Popov
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance TriviaNikita Popov
 
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 WayAlexis Gallagher
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
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-CAlexis Gallagher
 
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 developmentopenak
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming PatternsVasil Remeniuk
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP LanguageAhmed Ali
 
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?"Fwdays
 

What's hot (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?"
 

Similar to Working with Cocoa and Objective-C

Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Swift와 Objective-C를 함께 쓰는 방법
Swift와 Objective-C를 함께 쓰는 방법Jung Kim
 
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 APIsSubhransu Behera
 
Cappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkCappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkAndreas Korth
 
Migrating Objective-C to Swift
Migrating Objective-C to SwiftMigrating Objective-C to Swift
Migrating Objective-C to SwiftElmar Kretzer
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to DistributionTunvir Rahman Tusher
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overviewFantageek
 
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
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOSPetr Dvorak
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development IntroLuis Azevedo
 
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 2014Fábio Pimentel
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsPetr Dvorak
 
MFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsMFF UK - Advanced iOS Topics
MFF UK - Advanced iOS TopicsPetr Dvorak
 
The Dark Side of Objective-C
The Dark Side of Objective-CThe Dark Side of Objective-C
The Dark Side of Objective-CMartin Kiss
 

Similar to 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
 

Recently uploaded

Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckMarc Lester
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationElement34
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Soroosh Khodami
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletAndrea Goulet
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksJinanKordab
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringPrakhyath Rai
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In hararekasambamuno
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabbereGrabber
 
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...Abortion Clinic
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConNatan Silnitsky
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfSrushith Repakula
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Maxim Salnikov
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Andrea Goulet
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdftimtebeek1
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfMehmet Akar
 

Recently uploaded (20)

Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
Transformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with LinksTransformer Neural Network Use Cases with Links
Transformer Neural Network Use Cases with Links
 
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements Engineering
 
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
 
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
 
How to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabberHow to install and activate eGrabber JobGrabber
How to install and activate eGrabber JobGrabber
 
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeCon
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?Prompt Engineering - an Art, a Science, or your next Job Title?
Prompt Engineering - an Art, a Science, or your next Job Title?
 
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
Abortion Clinic Pretoria ](+27832195400*)[ Abortion Clinic Near Me ● Abortion...
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdf
 

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/