O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mastering macOS Programming

Book Description

Take your macOS Sierra to the next level using the latest tools, designs, and best coding practices while developing with Swift 3.0

About This Book

  • 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

Who This Book Is For

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.

What You Will Learn

  • Combine beautiful design with robust code for the very best user experience
  • Bring the best coding practices to the new macOS Sierra
  • See what's new in Swift 3.0 and how best to leverage the Swift language
  • Master Apple's tools, including Xcode, Interface Builder, and Instruments
  • Use Unix and other common command-line tools to increase productivity
  • Explore the essential Cocoa frameworks, including networking, animation, audio, and video

In Detail

macOS continues to lead the way in desktop operating systems, with its tight integration across the Apple ecosystem of platforms and devices. With this book, you will get an in-depth knowledge of working on macOS, enabling you to unleash the full potential of the latest version using Swift 3 to build applications.

This book will help you broaden your horizons by taking your programming skills to next level. The initial chapters will show you all about the environment that surrounds a developer at the start of a project. It introduces you to the new features that Swift 3 and Xcode 8 offers and also covers the common design patterns that you need to know for planning anything more than trivial projects. You will then learn the advanced Swift programming concepts, including memory management, generics, protocol orientated and functional programming and with this knowledge you will be able to tackle the next several chapters that deal with Apple's own Cocoa frameworks. It also covers AppKit, Foundation, and Core Data in detail which is a part of the Cocoa umbrella framework. The rest of the book will cover the challenges posed by asynchronous programming, error handling, debugging, and many other areas that are an indispensable part of producing software in a professional environment.

By the end of this book, you will be well acquainted with Swift, Cocoa, and AppKit, as well as a plethora of other essential tools, and you will be ready to tackle much more complex and advanced software projects.

Style and approach

This comprehensive guide takes a hands-on practical approach incorporating a visually-rich format rather than a text heavy format. The focus is on teaching the core concepts through a series of small projects and standalone examples so you gain expertise with various aspects of macOS application development.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

Table of Contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
    6. Customer support
      1. Downloading the example code
      2. Downloading the color images of this book
      3. Errata
      4. Piracy
      5. Questions
  2. Hello macOS
    1. It's going to be Swift
    2. And more than Swift
    3. It's going to be Xcode and more
      1. Prerequisites
    4. The book's overall structure
      1. How Unix, macOS, Cocoa, and AppKit fit together
        1. Darwin
        2. macOS
        3. Cocoa
      2. Harnessing that power
    5. The serious developer's toolkit
    6. What you'll get from this book
    7. Summary
  3. Basic Swift
    1. Variables and types
      1. Number types
        1. Integers
      2. Booleans
      3. Strings
        1. Printing to the console
    2. Comments
    3. Arrays, dictionaries, and sets
      1. Arrays
      2. Dictionaries
      3. Sets
      4. Naming of types and variables
        1. Type aliases
    4. Value and reference types
    5. Operators
      1. Mathematical operators
        1. Augmented assignment
      2. Comparison operators
      3. Logical operators
      4. Other standard operators
        1. Ternary operator
        2. Nil-coalescing operator
    6. Structs, classes, and other data structures
      1. Structs
      2. Classes
        1. Optional instances
      3. Tuples
    7. Enumerations
    8. Optionals
      1. Why use optionals?
      2. Unwrapping an optional
    9. Control flow
      1. if else
      2. switch
      3. Loops
        1. Saying goodbye to i++
        2. Iterating with for loops
        3. while
    10. Functions
    11. Summary
  4. Checking Out the Power of Xcode
    1. A quick and simple sketch app
    2. Speeding it up with code snippets
      1. Checking out the supplied snippets
      2. Usage
      3. Rolling your own snippets
    3. Logging with special literals
    4. Getting the most out of breakpoints
      1. Editing breakpoint options
        1. Other actions
          1. Adding a debugger command
          2. Triggering an AppleScript or shell script
      2. Don't stop me now
    5. Behaviors
    6. Understanding schemes
      1. What schemes actually do
      2. Creating a new scheme
        1. Using scheme environment variables
    7. Why build configs are so cool
      1. Creating a new build configuration
      2. Creating user-defined build settings
        1. Adapting the Info.plist file
      3. Using Swift compiler custom flags
        1. Creating the custom flag
        2. Using custom flags in code
        3. Finding the build settings on disk
    8. Summary
  5. MVC and Other Design Patterns
    1. Programming paradigms
      1. So, what is meant by paradigm?
      2. Imperative
        1. Object-oriented programming
        2. Class-based programming
        3. Protocol-oriented programming
        4. The drawbacks of OOP
      3. Declarative programming
        1. Understanding functional programming
        2. Using functional concepts within OOP
        3. Learning functional programming the fast way
    2. Encapsulation
      1. Separation of concerns
      2. Simplification
    3. A path through the forest
      1. Functions
      2. Data flow
      3. Objects
      4. Design patterns
    4. Summary
  6. Advanced Swift
    1. Control flow
      1. Using switch
        1. Compound cases
        2. Tuple matching
        3. Value binding
        4. Using the where keyword
        5. Control transfer statements
          1. The break statement
          2. The fallthrough statement
      2. The guard statement
    2. Functions
      1. Arguments
        1. Default arguments
        2. Anonymous arguments
        3. Variadic arguments
        4. Function overloading
        5. Function naming in Swift 3.0
      2. First class functions
        1. Functions are typed
        2. Closures
          1. Closures that take arguments
          2. Closures with multiple arguments
          3. Alternative closure syntax
          4. Closures are functions; functions are closures
        3. Using map, reduce, and filter
          1. Map with arrays
          2. Map with dictionaries
          3. reduce
          4. filter
        4. Nesting and chaining map, reduce, and filter
          1. Nesting
          2. Chaining
    3. Enumerations as data structures
      1. Adding methods to enums
      2. Associated values
        1. Grouping together different data types
        2. Creating multiple distinct types from a single type
        3. Mixed type arrays, anybody?
      3. Recursive definitions
      4. Making constants with an enum
      5. Replacing classes
    4. Protocols
      1. Declaring method requirements
      2. Conforming to a protocol
      3. Protocol advantages over classes
        1. Extending existing types with a protocol
        2. Creating collections of mixed types
      4. Protocols can conform to protocols
      5. Declaring required properties
      6. Implementing required properties
      7. Class-only protocols
        1. Class considerations
      8. Protocol composition
    5. Customizing operators
      1. Adding operator implementations to types
        1. Equivalence
      2. Custom operators
        1. Defining a custom operator
          1. Prefix operators
          2. Postfix operators
          3. Infix operators
        2. Implementing a custom operator
    6. Collection types
      1. Arrays
        1. Comparing arrays
        2. Mutating an array
        3. Using arrays to create new arrays
        4. Testing array elements
        5. Removing elements from an array
          1. Methods that mutate and return a value
          2. Mutating non-returning methods
        6. Sorting arrays
      2. Dictionaries
        1. Accessing all keys or values
        2. Mutating dictionaries
        3. Removing dictionary elements
    7. Optionals
      1. Conditional downcasting
      2. Unwrapping optionals with guard
      3. Implicitly unwrapped optionals
    8. Summary
  7. Cocoa Frameworks - The Backbone of Your Apps
    1. Understanding Foundation Kit
      1. Understanding NSObject
    2. Import statements
    3. Leveraging key-value observing
      1. Coding for KVO
        1. KVO - compliant classes
        2. Adding the observer
        3. Reacting to value changes
        4. Removing the observer
      2. Trying it out
        1. Modifying ViewController
    4. Cocoa bindings
      1. Adding the data model
      2. Adding an NSArrayController
      3. Binding the table view
      4. Binding the table selection
        1. Adding the binding
        2. Adding and binding a text field
      5. Changing array values
      6. Pretty Boolean
    5. Summary
  8. Creating Views Programmatically
    1. Why code instead of IB?
    2. Setting our goals
      1. The steps involved
        1. Beyond the visuals
    3. Coding a table view
      1. Preparing the View Controller
      2. The table and label
        1. Adding the table
        2. Configuring the table's columns
        3. Adding the info label
      3. Providing the app with data
        1. Importing the Person class
        2. The data model
        3. Creating a property list with XML
        4. Getting data from the property list
      4. Adopting datasource and delegate protocols
        1. Datasource extension
        2. Delegate extension
          1. Returning table view columns
        3. Reacting to selection events
    4. Observing without bindings
      1. Adding KVO to the View Controller
        1. Adding an observer
        2. Handling changes in the data
        3. Removing an observer
        4. Triggering changes to the data
      2. Advantages of KVO in code
      3. The final line of code
    5. Adding further control elements in code
      1. Adding the sort button
      2. Implementing a button's action
      3. Running the app
    6. Summary
  9. Strings and Text
    1. Strings and characters
      1. What is a String in Swift?
      2. What is a Character?
        1. Unicode compliance
        2. Combining strings and characters
      3. String indices and subranges
        1. Obtaining a String.Index
        2. Obtaining a subrange
      4. Modifying strings
        1. Removing characters
        2. Inserting characters
      5. String interpolation
        1. Writing long strings
      6. Escape characters
      7. Other representations
      8. C strings
      9. NSString
        1. Some NSString gotchas
          1. Indexing
          2. Mutability
          3. Value and reference
      10. String comparison
      11. Formatting strings
        1. Formatting using fonts
        2. Formatting using NSMutableAttributedString
          1. Adding an attribute
          2. Multiple attributes
          3. Links in text
          4. Styles and effects
    2. NSTextView
      1. The MVC pattern of text views
        1. NSTextStorage
        2. NSTextContainer
        3. NSLayoutManager
      2. Custom text view
        1. Creating the custom storage class
        2. Creating the custom text view
    3. Summary
  10. Getting More from Interface Builder
    1. Advanced IB navigation
      1. The little-known HUD
      2. Showing all views under the cursor
    2. Debug View Hierarchy
      1. Controlling the amount of information
      2. Other view settings
        1. Wireframe view
        2. Zooming
        3. Showing constraints
    3. Encapsulating views with NSStackView
    4. Taming the storyboard
      1. Refactoring large storyboards
      2. Under the hood of a storyboard
    5. Summary
  11. Drawing on the Strength of Core Graphics
    1. Why not use an image?
    2. Why not use native views?
      1. Core Graphics and AppKit drawing
        1. Using AppKit
        2. Using Core Graphics
        3. Which to use
    3. Creating custom views
    4. Custom buttons
      1. Defining the custom button's properties
      2. Overriding the button's draw method
        1. Filling a path
        2. Stroking a path
        3. Drawing the icon with code
        4. Adding an alternative icon
        5. Testing the button
    5. Dial clock
      1. Creating a custom view with AppKit
      2. Overriding the custom view's draw method
        1. Drawing arcs
        2. Drawing the outline
        3. Adding the fill color
        4. Adding the minutes curve
        5. Adding the hours curve
        6. Correcting the order of drawing
    6. Pie clock
      1. Creating a custom view with Core Graphics
        1. Understanding CGContext
          1. Why do we need a graphics context?
        2. Understanding the CG coordinates system
      2. Creating the custom class
      3. Overriding the class's draw method
        1. The draw method
        2. The drawFace method
          1. Adding a gradient with AppKit
        3. The drawMinutes method
          1. Adding a gradient with Core Graphics
          2. Adding more color locations
        4. The drawHours method
          1. Context translation
          2. Context rotation
          3. Translating the context
          4. Rotating the text
        5. Adding the hour displacement
        6. Adding shadows
        7. Context scaling
    7. Summary
  12. Core Animation
    1. What is Core Animation?
      1. Where does Core Animation fit in?
        1. Layer backed and layer hosting
        2. Drawing, then animating
    2. Introducing CALayer
      1. Creating a project
        1. Adding a custom view
        2. Extending CGColor
        3. Preparing the ViewController class
        4. Adding a button in code
      2. Building CALayer objects
        1. Adding CA sublayers
        2. Exploring glows and shadows
        3. Adding a CAShapeLayer
          1. CAShapeLayer properties
          2. CGPaths
          3. Adding CA transformations
          4. Rotating a layer in 3D
        4. Using CATextLayer
    3. Animating CALayer objects
      1. CA implicit animations
      2. CA explicit animations
        1. CABasicAnimation
          1. CABasicAnimation and the view model
        2. Delaying an animation
        3. Using CAKeyframeAnimation
        4. Controlling animations with CAAnimationGroup
        5. Wrapping changes in CATransaction objects
          1. Affine transformation
          2. Adding CATransaction completion blocks
          3. Nesting CATransaction blocks
      3. Two-and-a-half dimensional animations
        1. Adding perspective
      4. Getting even closer to 3D
        1. Introducing CATransformLayer
        2. Composing CALayers onto CATransformLayer
        3. Rotating the CATransformLayer
        4. Adding 3D animation
    4. Animating NSViews
    5. Summary
  13. Handling Errors Gracefully
    1. Errors aren't mistakes
    2. Expecting the unexpected
      1. Optionals
      2. Explicit error handling
    3. Swift error handling
      1. The four ways of handling errors
      2. Error types
        1. Creating the simplest Error enum
        2. Creating a better Error enum
      3. Throwing an error
      4. Handling an error
        1. The error life cycle
        2. Asserting that the error will not occur
        3. Handling the error as an optional value
        4. Handling an error with do-catch
          1. Pattern matching
          2. Matching associated values
      5. Propagating an error
        1. Propagation - case study: handling in scope
        2. Propagation - case study: propagation
      6. Verbose errors
      7. Anything can be an error
    4. NSError handling
      1. Anatomy of an NSError
      2. Catching NSErrors
        1. Pattern-matched Cocoa catches
      3. Creating NSError instances in Swift
    5. Summary
  14. Persistent Storage
    1. Creating a project
      1. Creating the project's file manager
    2. Using UserDefaults
      1. Storage of simple objects
        1. Storing simple objects
          1. Using the synchronize method
        2. Loading simple objects
        3. Testing the code
      2. Storing structured data
        1. Saving structured data
        2. Loading structured data
        3. Testing the code
      3. Loading by type
        1. Testing the code
      4. UserDefaults convenience methods
        1. Saving with convenience methods
        2. Loading the data
        3. Testing the code
      5. Security considerations
    3. Saving text to the Documents folder
      1. Create an extension and helper function
      2. Storing textual data
      3. Testing the save function
      4. Loading text files
      5. Testing the load function
    4. NSCoding/NSKeyedArchiver
      1. Creating an NSCoding--compliant class
      2. Handling NSCoding--compliant objects
        1. Saving NSCoding--compliant objects
        2. Loading NSCoding--compliant objects
        3. Testing the code
      3. More complex objects
    5. Presenting open and save dialog boxes
    6. Summary
  15. The Benefits of Core Data
    1. What Core Data is, and isn't
      1. Elements of a Core Data model
        1. Entities
        2. Attributes
        3. Relationships
    2. Core Data, Cocoa Bindings, and no code
      1. Create the project
      2. Create a simple UI in Interface Builder
        1. Adding the necessary UI objects to the Scene
        2. Add an Array Controller
      3. Setting up the data model
        1. Preparing the View Controller
      4. Connecting up to the storyboard
        1. Connecting the buttons
        2. Connecting the Array Controller
        3. Setting up the table columns
        4. Connecting the Table Cell Views
        5. Connecting the text fields
    3. Using our data model
      1. Using NSPersistenceContainer
        1. Adding an NSPersistentContainer instance
        2. Delete the unneeded properties
        3. Replacing references to the context
      2. Creating a data manager class
      3. Non-string entity attributes
        1. Creating entity instances
        2. What is a managed object context?
      4. Fetching data
      5. Adding relationships between entities
        1. One-to-one relationships
        2. One-to-many relationships
          1. Adding relationships to the crew
          2. Same thing, the other way around
      6. Sorted fetches
        1. Sorting in the table view
        2. Predicate fetching
        3. Using other predicates
          1. Searching for a string
          2. Searching for a case - insensitive string
          3. Combining predicates
          4. Relationship predicates
        4. Deleting the red guy
    4. More about Core Data
      1. The Core Data stack
        1. NSManagedObjectModel
        2. NSManagedObjectContext
        3. NSPersistentStoreCoordinator
      2. Does app X really need Core Data?
        1. The pros
        2. The cons
        3. Making that decision
    5. Summary
  16. Connect to the World - Networking
    1. Patterns for downloading data
      1. Simplicity
      2. Control
    2. Downloading using closures
      1. Starting a local test server on your machine
        1. Starting the server
        2. Creating a JSON file
        3. Testing the server
      2. Implementing an HTTP request manager
        1. The web as an asynchronous entity
        2. The simplest request possible
          1. The completion handler
        3. Improving the simplest request possible
        4. Customizing URLSessionConfiguration properties
        5. Customizing URLRequest properties
        6. Customizing URLSessionTask properties
    3. Downloading using a URLSession delegate
      1. Adding HTTP compatibility to the app
      2. Creating a simple UI
      3. Creating the manager
      4. Creating a session delegate class
        1. URLSessionDownloadDelegate methods
        2. Handling the data
        3. Catching errors
        4. Getting progress information
      5. Canceling a download
        1. URLSessionTaskDelegate methods
      6. Adding suspend and resume
    4. No third-party frameworks?
    5. The URLSession framework
      1. URLSessionTasks
      2. Ephemeral sessions
    6. Cache rewards
      1. Using different request cache policies
    7. Summary
  17. Concurrency and Asynchronous Programming
    1. Concurrency and asynchronicity
      1. Concurrency
        1. Concurrency and parallelism
          1. Multithreading
          2. Multiprocessing
        2. Threads, and why you don't need to worry
      2. Asynchronicity
        1. The challenges of asynchronous programming
        2. Dependencies, and why you don't need to worry
      3. Operation framework
        1. Understanding operations and queues
          1. Basic use of an OperationQueue
          2. Adding dependencies to BlockOperations
          3. More BlockOperation features
          4. BlockOperation completion blocks
      4. Defining a custom Operation object
        1. Concurrent and non-concurrent operations
          1. Defining non-concurrent custom operations
          2. Defining concurrent custom operations
    2. Summary
  18. Understanding Xcodes Debugging Tools
    1. Checking out Xcode's debugging tools
      1. Debug area
        1. Variables view
          1. Using Quicklook
        2. Console view
      2. Debugging in the navigator area
        1. Debug navigator
          1. Hiding and showing additional information
          2. Changing the process view
        2. Breakpoint navigator
        3. Report navigator
    2. Leveraging breakpoints
      1. Different types of breakpoint
        1. Swift error breakpoints
        2. Symbolic breakpoints
        3. Other breakpoint types
      2. Adding and removing breakpoints
      3. Editing breakpoints
        1. Conditions
        2. Ignore
        3. Adding an action to a breakpoint
          1. Log message
          2. Debugger Command
          3. Shell Command
          4. AppleScript
          5. We can also get a little more ambitious with these actions
          6. Sounds
          7. Multiple actions
      4. Breakpoint control flow
        1. Debugger control
        2. Close
        3. Enable
        4. Continue
        5. Step over
        6. Step into
        7. Step out
        8. Trying them out
    3. Summary
  19. LLDB and the Command Line
    1. LLDB
      1. Using LLDB
      2. Debugging line-by-line
        1. Continue
        2. Step over
        3. Step into
        4. Step out
        5. Trying it out
        6. Enable
      3. Printing in LLDB
        1. Preparing classes for LLDB descriptions
        2. Stop hooks
        3. Printing formatted numbers
        4. Executing code from LLDB
        5. Type lookups
      4. Breakpoints in LLDB
        1. Adding a breakpoint
        2. Breakpoint list
        3. Attaching commands to breakpoints
        4. Creating a Swift Error breakpoint
        5. Naming breakpoints
      5. Watchpoints
        1. Adding conditions and commands
        2. Watchpoint lists
        3. Enabling, disabling, and deleting watchpoints
      6. Persistent customization
      7. Getting help in LLBD
      8. Using shell commands in LLDB
      9. REPL in LLDB
        1. Switching between LLDB and Swift REPL
        2. Leaving a REPL session
      10. Using Python in LLDB
        1. Accessing program variables from Python
        2. Switching between LLDB and Python REPL
        3. One liners from LLDB to Python
        4. Getting help in Python
      11. Altogether now
      12. Standalone LLDB
        1. Running Xcode projects in a standalone LLDB session
        2. Differences between standalone and Xcode LLDB
    2. Summary
  20. Deploying Third - Party Code
    1. Common use cases
    2. Distribution methods
      1. Third - party source code
      2. Third - party libraries
      3. Third-party frameworks
      4. But the Internet says...
    3. Pros and cons
      1. The case for third - party code
      2. The case against
      3. The take-away
        1. A case study
        2. Leaving it till later
    4. Different installation methods
      1. Manual source code integration
        1. Downloading the ZIP
        2. Cloning the repo
          1. Preparing to clone
          2. Installing Homebrew
          3. Installing Git
        3. Cloning the repository
        4. Importing the source code
      2. Swift Package Manager
        1. SPM products
        2. Adding the package to an Xcode project
        3. Over to Xcode
        4. Package baggage
    5. Other package managers
      1. Cocoapods
      2. Carthage
    6. The price of complexity
    7. Summary
  21. Wrapping It Up
    1. App distribution
      1. The right settings on project creation
        1. The product name
        2. Team
        3. The Organization Identifier
        4. Bundle ID
      2. Setting up the project
        1. Setting the Application Category
        2. Enabling sandboxing
      3. Your developer account
        1. Registering an app ID
      4. Providing the required icons
      5. Archiving the app
      6. Validating the archive
      7. Uploading to the App Store
        1. Creating app records in iTunes Connect
        2. Uploading from Xcode to the App Store
      8. Exporting the app for distribution
        1. Save for Mac App Store Deployment
          1. Testing the Installer package
        2. Export a Developer ID-signed Application
        3. Export a Development-signed Application
        4. Export as a macOS App
    2. Summary
    3. And finally
      1. The book website