Mastering macOS Programming
()
About this ebook
- Learn to harness the power of macOS with the elegance of the Swift programming language
- Become highly competent in building apps on the macOS platform
- Get the most in-depth guide with a hands-on approach on the latest version of macOS
This book is for developers who have some experience with macOS and want to take their skills to next level by unlocking the full potential of latest version of macOS with Swift 3 to build impressive applications. Basic knowledge of Swift will be beneficial but is not required.
Related to Mastering macOS Programming
Related ebooks
Mastering Swift 5 - Fifth Edition: Deep dive into the latest edition of the Swift programming language, 5th Edition Rating: 0 out of 5 stars0 ratingsLearning Swift - Second Edition Rating: 0 out of 5 stars0 ratingsSwift Functional Programming - Second Edition Rating: 3 out of 5 stars3/5Learning Swift Rating: 5 out of 5 stars5/5Swift Essentials Rating: 0 out of 5 stars0 ratingsApplication Development with Swift Rating: 0 out of 5 stars0 ratingsBuilding Python Real-Time Applications with Storm Rating: 0 out of 5 stars0 ratingsComprehensive Ruby Programming Rating: 0 out of 5 stars0 ratingsMastering Linux Shell Scripting Rating: 4 out of 5 stars4/5iOS 13 Programming for Beginners - Fourth Edition: Get started with building iOS apps with Swift 5 and Xcode 11, 4th Edition Rating: 0 out of 5 stars0 ratingsThe Mac Terminal Reference and Scripting Primer Rating: 4 out of 5 stars4/5Getting Started With Ubuntu OS: A Ridiculously Simple Guide to the Linux Open Source Operating System Rating: 0 out of 5 stars0 ratingsSwift by Example Rating: 1 out of 5 stars1/5Mac Application Development For Dummies Rating: 0 out of 5 stars0 ratingsProfessional C# 7 and .NET Core 2.0 Rating: 0 out of 5 stars0 ratingsSwiftUI For Dummies Rating: 0 out of 5 stars0 ratingsC# Mastery: A Comprehensive Guide to Programming in C# Rating: 0 out of 5 stars0 ratingsCore Objective-C in 24 Hours Rating: 5 out of 5 stars5/5Principles of Programming: Java Level 1 Rating: 0 out of 5 stars0 ratingsThe Ruby Workshop: Develop powerful applications by writing clean, expressive code with Ruby and Ruby on Rails Rating: 0 out of 5 stars0 ratings42 Astoundingly Useful Scripts and Automations for the Macintosh Rating: 0 out of 5 stars0 ratingsPowerShell A Complete Guide - 2021 Edition Rating: 0 out of 5 stars0 ratingsCross-Platform Desktop Applications: Using Node, Electron, and NW.js Rating: 0 out of 5 stars0 ratingsGit Version Control Cookbook Rating: 4 out of 5 stars4/5iOS 10 Programming for Beginners Rating: 5 out of 5 stars5/5Test-Driven iOS Development with Swift Rating: 5 out of 5 stars5/5Mastering Rust Programming: From Foundations to Future Rating: 0 out of 5 stars0 ratingsMastering Xamarin.Forms Rating: 3 out of 5 stars3/5Ruby Developers Guide Rating: 3 out of 5 stars3/5iOS 15 Application Development for Beginners: Learn Swift Programming and Build iPhone Apps with SwiftUI and Xcode 13 Rating: 0 out of 5 stars0 ratings
Programming For You
Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5Java for Beginners: A Crash Course to Learn Java Programming in 1 Week Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Unreal Engine from Zero to Proficiency (Foundations): Unreal Engine from Zero to Proficiency, #1 Rating: 0 out of 5 stars0 ratingsCoding All-in-One For Dummies Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Python Projects for Beginners: A Ten-Week Bootcamp Approach to Python Programming Rating: 0 out of 5 stars0 ratingsHTML in 30 Pages Rating: 5 out of 5 stars5/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsProfessional C++ Rating: 2 out of 5 stars2/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5
Reviews for Mastering macOS Programming
0 ratings0 reviews
Book preview
Mastering macOS Programming - Grimshaw Stuart
Title Page
Mastering macOS Programming
Combine macOS programming with Cocoa and Swift 3 to build powerful applications
Stuart Grimshaw
BIRMINGHAM - MUMBAI
Copyright
Mastering macOS Programming
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2017
Production reference: 1300517
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-169-8
www.packtpub.com
Credits
About the Author
Stuart Grimshaw has programmed for Apple computers since the days before OS X and has been involved with developing for the Apple Watch since its release. Born in the UK and having lived in Germany and the Netherlands, he is currently a freelance iOS/tvOS/macOS developer in Auckland, New Zealand, where he works on some of Australia-New Zealand's largest video and TV delivery apps and leads the research and development of both watchOS and tvOS applications. He is passionate about the potential of the Apple Watch and Apple TV, as well as Apple's Swift programming language, and is a keen proponent of beach coding.
About the Reviewer
Fernando Rodríguez has more than 20 years of experience in developing and teaching other developers. Although he currently specializes in the Apple stack of tools, he’s a nerd of all trades with a strong interest in big data and automated trading.
He has taught iOS development at the Big Nerd Ranch, Udacity, and Keepcoding, ranging from Facebook developers to indie devs.
He was awarded as an Outstanding instructor
at Udemy for his introductory course to iOS development. This course was mentioned in the Financial Times, Venture beat, and InformationWeek.
Code long and prosper!
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1786461692.
If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Dedication
For Jane.
And because this book is twice as thick as the last one, for my mum too.
Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Hello macOS
It's going to be Swift
And more than Swift
It's going to be Xcode and more
Prerequisites
The book's overall structure
How Unix, macOS, Cocoa, and AppKit fit together
Darwin
macOS
Cocoa
Harnessing that power
The serious developer's toolkit
What you'll get from this book
Summary
Basic Swift
Variables and types
Number types
Integers
Booleans
Strings
Printing to the console
Comments
Arrays, dictionaries, and sets
Arrays
Dictionaries
Sets
Naming of types and variables
Type aliases
Value and reference types
Operators
Mathematical operators
Augmented assignment
Comparison operators
Logical operators
Other standard operators
Ternary operator
Nil-coalescing operator
Structs, classes, and other data structures
Structs
Classes
Optional instances
Tuples
Enumerations
Optionals
Why use optionals?
Unwrapping an optional
Control flow
if else
switch
Loops
Saying goodbye to i++
Iterating with for loops
while
Functions
Summary
Checking Out the Power of Xcode
A quick and simple sketch app
Speeding it up with code snippets
Checking out the supplied snippets
Usage
Rolling your own snippets
Logging with special literals
Getting the most out of breakpoints
Editing breakpoint options
Other actions
Adding a debugger command
Triggering an AppleScript or shell script
Don't stop me now
Behaviors
Understanding schemes
What schemes actually do
Creating a new scheme
Using scheme environment variables
Why build configs are so cool
Creating a new build configuration
Creating user-defined build settings
Adapting the Info.plist file
Using Swift compiler custom flags
Creating the custom flag
Using custom flags in code
Finding the build settings on disk
Summary
MVC and Other Design Patterns
Programming paradigms
So, what is meant by paradigm?
Imperative
Object-oriented programming
Class-based programming
Protocol-oriented programming
The drawbacks of OOP
Declarative programming
Understanding functional programming
Using functional concepts within OOP
Learning functional programming the fast way
Encapsulation
Separation of concerns
Simplification
A path through the forest
Functions
Data flow
Objects
Design patterns
Summary
Advanced Swift
Control flow
Using switch
Compound cases
Tuple matching
Value binding
Using the where keyword
Control transfer statements
The break statement
The fallthrough statement
The guard statement
Functions
Arguments
Default arguments
Anonymous arguments
Variadic arguments
Function overloading
Function naming in Swift 3.0
First class functions
Functions are typed
Closures
Closures that take arguments
Closures with multiple arguments
Alternative closure syntax
Closures are functions; functions are closures
Using map, reduce, and filter
Map with arrays
Map with dictionaries
reduce
filter
Nesting and chaining map, reduce, and filter
Nesting
Chaining
Enumerations as data structures
Adding methods to enums
Associated values
Grouping together different data types
Creating multiple distinct types from a single type
Mixed type arrays, anybody?
Recursive definitions
Making constants with an enum
Replacing classes
Protocols
Declaring method requirements
Conforming to a protocol
Protocol advantages over classes
Extending existing types with a protocol
Creating collections of mixed types
Protocols can conform to protocols
Declaring required properties
Implementing required properties
Class-only protocols
Class considerations
Protocol composition
Customizing operators
Adding operator implementations to types
Equivalence
Custom operators
Defining a custom operator
Prefix operators
Postfix operators
Infix operators
Implementing a custom operator
Collection types
Arrays
Comparing arrays
Mutating an array
Using arrays to create new arrays
Testing array elements
Removing elements from an array
Methods that mutate and return a value
Mutating non-returning methods
Sorting arrays
Dictionaries
Accessing all keys or values
Mutating dictionaries
Removing dictionary elements
Optionals
Conditional downcasting
Unwrapping optionals with guard
Implicitly unwrapped optionals
Summary
Cocoa Frameworks - The Backbone of Your Apps
Understanding Foundation Kit
Understanding NSObject
Import statements
Leveraging key-value observing
Coding for KVO
KVO - compliant classes
Adding the observer
Reacting to value changes
Removing the observer
Trying it out
Modifying ViewController
Cocoa bindings
Adding the data model
Adding an NSArrayController
Binding the table view
Binding the table selection
Adding the binding
Adding and binding a text field
Changing array values
Pretty Boolean
Summary
Creating Views Programmatically
Why code instead of IB?
Setting our goals
The steps involved
Beyond the visuals
Coding a table view
Preparing the View Controller
The table and label
Adding the table
Configuring the table's columns
Adding the info label
Providing the app with data
Importing the Person class
The data model
Creating a property list with XML
Getting data from the property list
Adopting datasource and delegate protocols
Datasource extension
Delegate extension
Returning table view columns
Reacting to selection events
Observing without bindings
Adding KVO to the View Controller
Adding an observer
Handling changes in the data
Removing an observer
Triggering changes to the data
Advantages of KVO in code
The final line of code
Adding further control elements in code
Adding the sort button
Implementing a button's action
Running the app
Summary
Strings and Text
Strings and characters
What is a String in Swift?
What is a Character?
Unicode compliance
Combining strings and characters
String indices and subranges
Obtaining a String.Index
Obtaining a subrange
Modifying strings
Removing characters
Inserting characters
String interpolation
Writing long strings
Escape characters
Other representations
C strings
NSString
Some NSString gotchas
Indexing
Mutability
Value and reference
String comparison
Formatting strings
Formatting using fonts
Formatting using NSMutableAttributedString
Adding an attribute
Multiple attributes
Links in text
Styles and effects
NSTextView
The MVC pattern of text views
NSTextStorage
NSTextContainer
NSLayoutManager
Custom text view
Creating the custom storage class
Creating the custom text view
Summary
Getting More from Interface Builder
Advanced IB navigation
The little-known HUD
Showing all views under the cursor
Debug View Hierarchy
Controlling the amount of information
Other view settings
Wireframe view
Zooming
Showing constraints
Encapsulating views with NSStackView
Taming the storyboard
Refactoring large storyboards
Under the hood of a storyboard
Summary
Drawing on the Strength of Core Graphics
Why not use an image?
Why not use native views?
Core Graphics and AppKit drawing
Using AppKit
Using Core Graphics
Which to use
Creating custom views
Custom buttons
Defining the custom button's properties
Overriding the button's draw method
Filling a path
Stroking a path
Drawing the icon with code
Adding an alternative icon
Testing the button
Dial clock
Creating a custom view with AppKit
Overriding the custom view's draw method
Drawing arcs
Drawing the outline
Adding the fill color
Adding the minutes curve
Adding the hours curve
Correcting the order of drawing
Pie clock
Creating a custom view with Core Graphics
Understanding CGContext
Why do we need a graphics context?
Understanding the CG coordinates system
Creating the custom class
Overriding the class's draw method
The draw method
The drawFace method
Adding a gradient with AppKit
The drawMinutes method
Adding a gradient with Core Graphics
Adding more color locations
The drawHours method
Context translation
Context rotation
Translating the context
Rotating the text
Adding the hour displacement
Adding shadows
Context scaling
Summary
Core Animation
What is Core Animation?
Where does Core Animation fit in?
Layer backed and layer hosting
Drawing, then animating
Introducing CALayer
Creating a project
Adding a custom view
Extending CGColor
Preparing the ViewController class
Adding a button in code
Building CALayer objects
Adding CA sublayers
Exploring glows and shadows
Adding a CAShapeLayer
CAShapeLayer properties
CGPaths
Adding CA transformations
Rotating a layer in 3D
Using CATextLayer
Animating CALayer objects
CA implicit animations
CA explicit animations
CABasicAnimation
CABasicAnimation and the view model
Delaying an animation
Using CAKeyframeAnimation
Controlling animations with CAAnimationGroup
Wrapping changes in CATransaction objects
Affine transformation
Adding CATransaction completion blocks
Nesting CATransaction blocks
Two-and-a-half dimensional animations
Adding perspective
Getting even closer to 3D
Introducing CATransformLayer
Composing CALayers onto CATransformLayer
Rotating the CATransformLayer
Adding 3D animation
Animating NSViews
Summary
Handling Errors Gracefully
Errors aren't mistakes
Expecting the unexpected
Optionals
Explicit error handling
Swift error handling
The four ways of handling errors
Error types
Creating the simplest Error enum
Creating a better Error enum
Throwing an error
Handling an error
The error life cycle
Asserting that the error will not occur
Handling the error as an optional value
Handling an error with do-catch
Pattern matching
Matching associated values
Propagating an error
Propagation - case study: handling in scope
Propagation - case study: propagation
Verbose errors
Anything can be an error
NSError handling
Anatomy of an NSError
Catching NSErrors
Pattern-matched Cocoa catches
Creating NSError instances in Swift
Summary
Persistent Storage
Creating a project
Creating the project's file manager
Using UserDefaults
Storage of simple objects
Storing simple objects
Using the synchronize method
Loading simple objects
Testing the code
Storing structured data
Saving structured data
Loading structured data
Testing the code
Loading by type
Testing the code
UserDefaults convenience methods
Saving with convenience methods
Loading the data
Testing the code
Security considerations
Saving text to the Documents folder
Create an extension and helper function
Storing textual data
Testing the save function
Loading text files
Testing the load function
NSCoding/NSKeyedArchiver
Creating an NSCoding--compliant class
Handling NSCoding--compliant objects
Saving NSCoding--compliant objects
Loading NSCoding--compliant objects
Testing the code
More complex objects
Presenting open and save dialog boxes
Summary
The Benefits of Core Data
What Core Data is, and isn't
Elements of a Core Data model
Entities
Attributes
Relationships
Core Data, Cocoa Bindings, and no code
Create the project
Create a simple UI in Interface Builder
Adding the necessary UI objects to the Scene
Add an Array Controller
Setting up the data model
Preparing the View Controller
Connecting up to the storyboard
Connecting the buttons
Connecting the Array Controller
Setting up the table columns
Connecting the Table Cell Views
Connecting the text fields
Using our data model
Using NSPersistenceContainer
Adding an NSPersistentContainer instance
Delete the unneeded properties
Replacing references to the context
Creating a data manager class
Non-string entity attributes
Creating entity instances
What is a managed object context?
Fetching data
Adding relationships between entities
One-to-one relationships
One-to-many relationships
Adding relationships to the crew
Same thing, the other way around
Sorted fetches
Sorting in the table view
Predicate fetching
Using other predicates
Searching for a string
Searching for a case - insensitive string
Combining predicates
Relationship predicates
Deleting the red guy
More about Core Data
The Core Data stack
NSManagedObjectModel
NSManagedObjectContext
NSPersistentStoreCoordinator
Does app X really need Core Data?
The pros
The cons
Making that decision
Summary
Connect to the World - Networking
Patterns for downloading data
Simplicity
Control
Downloading using closures
Starting a local test server on your machine
Starting the server
Creating a JSON file
Testing the server
Implementing an HTTP request manager
The web as an asynchronous entity
The simplest request possible
The completion handler
Improving the simplest request possible
Customizing URLSessionConfiguration properties
Customizing URLRequest properties
Customizing URLSessionTask properties
Downloading using a URLSession delegate
Adding HTTP compatibility to the app
Creating a simple UI
Creating the manager
Creating a session delegate class
URLSessionDownloadDelegate methods
Handling the data
Catching errors
Getting progress information
Canceling a download
URLSessionTaskDelegate methods
Adding suspend and resume
No third-party frameworks?
The URLSession framework
URLSessionTasks
Ephemeral sessions
Cache rewards
Using different request cache policies
Summary
Concurrency and Asynchronous Programming
Concurrency and asynchronicity
Concurrency
Concurrency and parallelism
Multithreading
Multiprocessing
Threads, and why you don't need to worry
Asynchronicity
The challenges of asynchronous programming
Dependencies, and why you don't need to worry
Operation framework
Understanding operations and queues
Basic use of an OperationQueue
Adding dependencies to BlockOperations
More BlockOperation features
BlockOperation completion blocks
Defining a custom Operation object
Concurrent and non-concurrent operations
Defining non-concurrent custom operations
Defining concurrent custom operations
Summary
Understanding Xcodes Debugging Tools
Checking out Xcode's debugging tools
Debug area
Variables view
Using Quicklook
Console view
Debugging in the navigator area
Debug navigator
Hiding and showing additional information
Changing the process view
Breakpoint navigator
Report navigator
Leveraging breakpoints
Different types of breakpoint
Swift error breakpoints
Symbolic breakpoints
Other breakpoint types
Adding and removing breakpoints
Editing breakpoints
Conditions
Ignore
Adding an action to a breakpoint
Log message
Debugger Command
Shell Command
AppleScript
We can also get a little more ambitious with these actions
Sounds
Multiple actions
Breakpoint control flow
Debugger control
Close
Enable
Continue
Step over
Step into
Step out
Trying them out
Summary
LLDB and the Command Line
LLDB
Using LLDB
Debugging line-by-line
Continue
Step over
Step into
Step out
Trying it out
Enable
Printing in LLDB
Preparing classes for LLDB descriptions
Stop hooks
Printing formatted numbers
Executing code from LLDB
Type lookups
Breakpoints in LLDB
Adding a breakpoint
Breakpoint list
Attaching commands to breakpoints
Creating a Swift Error breakpoint
Naming breakpoints
Watchpoints
Adding conditions and commands
Watchpoint lists
Enabling, disabling, and deleting watchpoints
Persistent customization
Getting help in LLBD
Using shell commands in LLDB
REPL in LLDB
Switching between LLDB and Swift REPL
Leaving a REPL session
Using Python in LLDB
Accessing program variables from Python
Switching between LLDB and Python REPL
One liners from LLDB to Python
Getting help in Python
Altogether now
Standalone LLDB
Running Xcode projects in a standalone LLDB session
Differences between standalone and Xcode LLDB
Summary
Deploying Third - Party Code
Common use cases
Distribution methods
Third - party source code
Third - party libraries
Third-party frameworks
But the Internet says...
Pros and cons
The case for third - party code
The case against
The take-away
A case study
Leaving it till later
Different installation methods
Manual source code integration
Downloading the ZIP
Cloning the repo
Preparing to clone
Installing Homebrew
Installing Git
Cloning the repository
Importing the source code
Swift Package Manager
SPM products
Adding the package to an Xcode project
Over to Xcode
Package baggage
Other package managers
Cocoapods
Carthage
The price of complexity
Summary
Wrapping It Up
App distribution
The right settings on project creation
The product name
Team
The Organization Identifier
Bundle ID
Setting up the project
Setting the Application Category
Enabling sandboxing
Your developer account
Registering an app ID
Providing the required icons
Archiving the app
Validating the archive
Uploading to the App Store
Creating app records in iTunes Connect
Uploading from Xcode to the App Store
Exporting the app for distribution
Save for Mac App Store Deployment
Testing the Installer package
Export a Developer ID-signed Application
Export a Development-signed Application
Export as a macOS App
Summary
And finally
The book website
Preface
This book will take your Swift programming skills to a level at which you can work as a professional software engineer, using a step-by-step approach, ensuring that the introduction of each new concept is preceded by a thorough understanding of those preceding it.
The book covers a range of technologies, particularly those that you'll typically need, if not on day one of a new project (or a new job), then at least pretty soon after. These include not just Apple's Xcode, but also the Terminal app, Git version control, package management, the Swift REPL, and the LLDB debugger, all of which are essential skills.
Each chapter focuses on a particular topic or technology, giving you a deep dive into the skills and know-how that will take your work to a professional standard, in terms of code quality, maintainability, and robustness. This entails general topics, such as programming paradigms and design patterns, a general look at the Cocoa frameworks and their place in the macOS ecosystem, and of course specific technologies around networking, storage, and advanced graphics and animation.
Furthermore, a significant portion of the text is devoted to such thorny issues as concurrency, asynchronous programming, and error handling.
By the end of this book, you will be able to confidently approach projects of much greater size and complexity, and be well placed to comfortably deal with the various issues that all programming inevitably brings with it.
Coding is a never-ending journey. This book aims to get you on the right track, and a fair way along it.
What this book covers
Chapter 1, Hello macOS, explores the context in which the rest of the book is set and takes a look at developing for Apple platforms in general, and the direction that development is heading in.
Chapter 2, Basic Swift, takes a broad, high-level view of the Swift programming language.
Chapter 3, Checking out the Power of Xcode, introduces some pro-orientated aspects of this powerful, integrated Development Environment created by Apple.
Chapter 4, MVC and Other Design Patterns, covers a number of ways to help you plan your projects, from high-level conceptual down to the benefits offered by different styles of programming at the code level.
Chapter 5, Advanced Swift, investigates some of Swift's more powerful language features and idioms.
Chapter 6, Cocoa Frameworks - The Backbone of Your Apps, covers the large palette of ready-written framework code that relieve many of the burdens of low-level coding and boilerplate.
Chapter 7, Creating Views Programmatically, is concerned with giving you total control of your user interface, by moving beyond the constraints of visual UI editing.
Chapter 8, Strings and Text, looks at how to master the all-important textual features that are part of nearly every app you'll write for macOS.
Chapter 9, Getting More from Interface Builder, gets you through the maze of functionality offered by Apple's user interface creation tool.
Chapter 10, Drawing on the Strength of Core Graphics, drops us down to some low-level drawing routines, when the preconfigured UI offerings just aren't enough.
Chapter 11, Core Animation, takes you to the heart of what makes macOS such a polished and visually engaging platform.
Chapter 12, Handling Errors Gracefully, deals with the various tools you have at your disposal to handle all eventualities in your app, to produce a smooth and frustration-free user experience.
Chapter 13, Persistent Storage, introduces some of the most commonly used scenarios for storing data on disk.
Chapter 14, The Benefits of Core Data, takes you deeper into structured data persistence, keeping that critical user data organized and quickly accessible.
Chapter 15, Connect to the World - Networking, looks at connecting your code to the Internet, using the web session frameworks that Cocoa provides.
Chapter 16, Concurrency and Asynchronous Programming, aims to set some best practices, as well as investigate the appropriate tools, for dealing with time-sensitive data flows.
Chapter 17, Understanding Xcode's Debugging Tools, helps you master some of the most important tools at our disposal--Xcode's debugging features--for those moments when it doesn't go quite like your plan.
Chapter 18, LLDB and the Command Line, takes you into, and demystifies, working in the terminal, where all the really good stuff lives.
Chapter 19, Deploying Third - Party Code, helps you understand the role of third-party frameworks and libraries, and how to productively integrate them into your codebase.
Chapter 20, Wrapping It Up, gets your code from your hard drive to the App Store, avoiding the most common pitfalls along the way.
What you need for this book
To create and build the code presented here, you will need nothing more than Apple’s Xcode software package, which you can download for free in the App Store, and a Mac to run it on. A number of other tools are introduced, such as the OS X Terminal app, which are already installed on your Mac.
Testing the code can be done on any installation of macOS.
Who this book is for
If you have intermediate knowledge of programming in Swift and are looking for the best way to take your development skills to a professional level, this book is just the right one for you.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: But what if we want to make changes to, say, the app's Build Settings, or even its Info.plist file? Can we do that too?
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Click Options, and ensure that Copy Items if Needed is ticked.
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-macOS-Programming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/MasteringmacOSProgramming_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.
Hello macOS
Goodbye and thank you OS X, hello and welcome macOS!
Sierra is here, also known as macOS 10.12. Apple's latest OS release, announced at the 2016 World Wide Developers Conference, offers the modern app developer more tools than ever with which to create engaging, productive, and entertaining apps for what an ever-increasing number of people deem the world's most advanced operating system.
Now that it's here, it seems it was a long time coming. Apple has renamed its desktop operating system to reflect its integral part in the Apple ecosystem, which comprises iOS, tvOS, watchOS, and finally macOS. This makes a lot of sense, since so much of what we know both as users and as developers from one platform is reflected in the others, sometimes very closely, sometimes adapted to differences in the hardware with which these platforms are used.
The cross-fertilization of Apple's platforms is rapidly increasing, giving new impetus to the desktop operating system that has in many ways taken a back seat to the mobile juggernaut that the iPhone and iPad represent. The massive adoption of mobile technologies has provided a spurt of innovation that Apple has begun to integrate seriously into what has become macOS. At the same time, decades of experience with macOS, then OS X, and now macOS have flowed into the mobile space as the processors in phones and other devices grow more powerful.
But although the name has changed, the OS is in every sense the next version of OS X, as the 10.12 version number makes clear. Visually, nothing has changed either; About This Mac still shows the same small info window--only the mountain has changed:
This is really a great time to be an app developer. It is no exaggeration to describe what is happening across the globe as the digital revolution, and whether we're interested in productivity, entertainment, dissemination of information, or any one of scores of other development genres, we find ourselves on extremely fertile ground. It seems there are as many opportunities out there as there are souls ready to take on the challenges of creating the software that continues to drive progress at a breathtaking pace.
When approaching macOS as a developer, you will be able to make use of any and all experience you may have with programming for OS X, and if your background is in iOS and/or one of the other platforms, you will also discover the great extent to which you can leverage the knowledge and skills you have developed on those platforms. Indeed, much of the code you write for one platform will be directly usable in another, with little or no adaptation necessary.
If you are coming from a non-Apple background, I think it is safe to say you will find developing in Swift for macOS a rewarding expansion of your skills. Swift is a rich, flexible and expressive language, but not one that is hard to learn. It has, to some extent, a syntactic similarity to many modern object-oriented programming languages such as Python and Java (okay, modern in comparison to earlier popular successes such as Lisp and Fortran).
In this first chapter, we will look at the following topics:
The Swift programming language
Xcode and other development tools
How this book is structured
Some prerequisites for getting the most from this book
What this book will do for you once you have read it
So, let's look at where this book is going to take you, and how it will get you there.
It's going to be Swift
In just a little over two years, Swift has become one of the software development world's most talked-about programming languages, and is even the most forked repository on GitHub (but then, how many new languages have the power of a multinational like Apple behind them?). The language has undergone (and is still undergoing) incredibly rapid evolution, guided principally by Chris Lattner and the team at Apple, but also by the wider community, since it was open-sourced in December 2015, with proposals for language changes by non-Apple developers being included in the release of version 3.0. This radical departure from Apple's usually secretive product development strategy has meant that Swift has already benefitted from the experience and perspective of a great number of developers of mixed backgrounds (in every sense), with Apple itself saying that release 3.0 contains work by a total of three hundred and sixty-odd contributors.
If you are coming to Swift from Objective C for the first time, you will find it a much more succinct and clear language, one that needs fewer lines of boilerplate code, not to mention fewer semicolons, than its predecessor. If your background is in Python, JavaScript, or Java (to name the obvious ones), you'll find the code much easier to understand at first glance than would have been the case with Objective C--this is a good time to add Apple's platforms to your portfolio.
The code in this book will be in Swift version 3. Readers familiar with Swift 2.2 or earlier will notice that much has changed in the new version. We will not go into the details of those changes explicitly here, although they will be apparent from the next chapter onwards.
And more than Swift
But whether you refer to yourself as a software engineer, app developer, or hacker, there is substantially more to the job than writing Swift code inside Xcode. We will also be looking at interacting with bash shells in Terminal, dealing with files in XML format, data returned from the Web in JSON format, a little HTML, and the odd sprinkling of other languages, which may be used outside Xcode to good advantage.
We won't be going into a great amount of depth in these peripheral topics (if they can even be considered peripheral), but we will present what is essentially needed to get the job done, and give the reader an idea of the role they play in the larger picture. The interested reader will find no shortage of books and web resources with which to expand on the information presented here. There are also a number of articles available on the website that accompanies this book: http://grimshaw.de/macOS-book.
It's going to be Xcode and more
Much of this book, particularly the later chapters, will look at leveraging the considerable power of the Xcode-integrated development environment, in order to familiarize the reader with many aspects of development that go beyond code writing, to include debugging, performance measurement and improvement, working with source control within a team, and many others.
Software development is rarely a matter of using one single program, and we will be utilizing several tools other than Xcode to get the most out of the time we spend coding, compiling, and testing our work. You might be pleased to learn that none of these tools are going to cost you any money (although like any other tool, they come at the cost of a certain amount of time to be invested in order to reach a moderate level of proficiency). You might be even more pleased to learn that we will be covering this ground step by step, and no previous knowledge is assumed.
Prerequisites
Despite the varied backgrounds that readers of this book are likely to have, we will make some broad assumptions about the level of skill and experience you bring with you. There are also some hardware requirements, though nothing you're unlikely to have already.
To be able to comfortably follow this book, you will need to have the following:
A reasonably high level of familiarity with the macOS/OS X operating system and its day-to-day use, including trackpad gestures (in addition to mouse clicks, obviously), the file system as accessed through the Finder, and the general features of both Apple and third-party software.
Some basic experience of programming using an object-oriented programming language such as Swift, Objective C, or Java.
An Apple computer running at least macOS Sierra, with Xcode