MANNING
Brendan G. Lim
WITH Jerry Cheung
AND Jeremy McAnally
IN ACTION
www.it-ebooks.info
MacRuby in Action
www.it-ebooks.info
www.it-ebooks.info
MacRuby in Action
BRENDAN G. LIM
WITH JERRY CHEUNG
AND JEREMY MCANALLY
MANNING
SHELTER ISLAND
www.it-ebooks.info
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 261
Shelter Island, NY 11964
Email: [email protected]
©2012 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
■
Using the delegate pattern 87
5
■
Notifications and implementing the observer pattern 104
6
■
Using key-value coding and key-value observing 120
7
■
Implementing persistence with Core Data 141
8
■
Core Animation basics 168
PART 3 MACRUBY EXTRAS 187
9
■
HotCocoa 189
10
■
MacRuby testing 203
11
■
MacRuby and the Mac App Store 216
www.it-ebooks.info
www.it-ebooks.info
vii
contents
preface xiii
acknowledgments xiv
Using Ruby and
Objective-C methods 26
■
Creating user interfaces 27
1.5 Hello World, part 2 28
Creating an Xcode project 29
■
Creating the interface 30
Creating the controller 32
■
Connecting the interface and
controller 34
1.6 Summary 35
2
Using Macirb and the Apple development tools 37
2.1 Using external libraries with MacRuby 38
Loading frameworks 38
■
Loading Objective-C libraries as
bundles 39
■
Loading Ruby gems 41
2.2 Exploring Macirb 42
Comparing the Ruby and MacRuby consoles 42
Working in the MacRuby console 43
■
Macirb tips
and tricks 43
2.3 Building a Pomodoro application in Xcode 47
Creating a new MacRuby project 47
■
Connecting
outlets and actions 82
■
Running and packaging the
application 83
3.4 Summary 84
www.it-ebooks.info
CONTENTS
ix
PART 2 TAKE IT FOR A SPIN 85
4
Using the delegate pattern 87
4.1 What are delegates? 88
How do delegate methods work? 88
■
Implementing the delegate
pattern 89
4.2 Delegation as an extension technique 92
Delegation the Cocoa way 93
■
Delegation using
Forwardable 93
4.3 Using delegation in a custom MacRuby web browser 94
Creating the browser interface 94
■
Setting up the
controller 95
■
Implementing delegate methods in the
Creating the script 116
■
Running the script 118
5.6 Summary 118
6
Using key-value coding and key-value observing 120
6.1 Simplifying code with key-value coding 121
Accessing object properties with KVC 121
■
Handling
unknown keys 123
■
Understanding key paths and collection
operators 125
www.it-ebooks.info
CONTENTS
x
6.2 Using KVO to implement observers 128
Adding and removing observers 128
■
Manually notifying
observers of changes 129
■
Responding to observed
objects 130
6.3 Building out the Product Inventory application 131
Creating the user interface 131
■
Using KVC to retrieve product
information 132
■
Creating the tasks
controller 161
■
Connecting the interface to the controller 164
Running the application and inspecting the persistent store 166
7.6 Summary 167
8
Core Animation basics 168
8.1 Introduction to Core Animation 169
What is Core Animation? 169
■
Class structure 169
Core Animation’s rendering architecture 170
■
Creating a
basic animation with Cocoa Animation 171
www.it-ebooks.info
CONTENTS
xi
8.2 Core Animation layers 173
Layer coordinate systems 174
■
Layer geometry 174
Layer content 175
8.3 Animating with Core Animation 179
Basic animations 179
■
Keyframe animations 181
Grouping animations 182
10.5 Summary 215
11
MacRuby and the Mac App Store 216
11.1 Introducing the Mac App Store 217
Benefits of releasing on the Mac App Store 217
■
Limitations
of the Mac App Store 218
www.it-ebooks.info
CONTENTS
xii
11.2 Knowing the App Store rules 219
Functionality 219
■
Metadata 219
■
Location 219
User interface 219
■
Privacy 220
■
Charities and
contributions 220
■
Legal requirements 220
11.3 Submitting a MacRuby application 220
Creating certificates 220
■
Registering your Mac App ID 223
Preparing icons and screenshots 224
When I was contacted by Manning to work on this book, I knew I’d be able to
reach many other individuals who were Rubyists and who wanted to create rich Mac
applications without having to use Objective-C. This book is meant for you if you love
the Ruby language and want to get into Mac development
B
RENDAN G. LIM
www.it-ebooks.info
xiv
acknowledgments
Putting together a book like this is no easy feat, and many people behind the scenes
worked countless hours to get the book into your hands. First and foremost, everyone
at Manning deserves all the thanks we can give them. Without them, we wouldn’t have
been able to create such a great book for you.
We interacted frequently with a few individuals from Manning and would like to
specifically mention them. We’d like to thank Troy Mott, our acquisitions editor, who
originally came to us to work on this book and helped us through thick and thin. Sara
Onstine, our development editor, guided us through the formalities of writing a book
like this. And Marjan Bace, our publisher, always challenged us to find ways to
improve the book’s content and organization.
We’d also like to thank our book’s production team. Lianna Wlasiuk, Tiffany Tay-
lor, and Melody Dolab, our copyeditors and proofreader, read the entire manuscript
and made sure everything was organized and presented properly. Nick Howard, our
technical proofreader, caught errors that we didn’t know were there.
Over the course of the development of the book, many people generously volun-
teered to review it to help make it as good as it could be. These reviewers deserve a tre-
mendous amount of credit for the impact they made through their feedback. Our
thanks to Pradeep Elankumaran, Brent Collier, Adam Bair, Philip Hallstrom, Mike
Stok, Alex Vollmer, Coby Randquist, Jerry Cheung, Greg Vaughn, Warner Onstine,
and Daniel Bretoi.
www.it-ebooks.info
It doesn’t matter if you’re new to both the Mac and the Ruby language or you’re an
experienced Ruby developer looking to learn how to write Mac apps. If you have the
desire to create beautiful Cocoa applications for the Mac platform and want to do so
using the elegant and highly productive Ruby language, then this book is for you. If
you’re new to Ruby, we give you a brief overview of the language so you’ll feel comfort-
able enough to take on the rest of the book.
MacRuby in Action is also a more approachable introduction to Cocoa development
than traditional Objective-C books. Throughout the book, we explore practical code
examples that you’ll face when creating your own applications. MacRuby in Action can
act as a guide for using MacRuby and Cocoa from the ground up, or you can use it as
a reference if you’re looking to dive deeper into MacRuby.
www.it-ebooks.info
ABOUT THIS BOOK
xvii
Roadmap
The book has 11 chapters divided into three parts as follows:
Chapter 1 explores the inner workings of MacRuby and how to set up your devel-
opment environment. There’s also an introduction to Ruby and an overview of
Objective-C syntax. We then go into the MacRuby syntax, give a few examples, and
end with two “Hello World” examples.
Chapter 2 takes a deeper dive into MacRuby with more in-depth examples. We
look into using external frameworks, Ruby gems, and the MacRuby console. At the
end of the chapter, you build a MacRuby Pomodoro application.
Chapter 3 talks about Apple’s development environment tools. You spend more
time using Xcode’s Interface Builder to create rich Cocoa user interfaces. You then
use your Interface Builder knowledge to create an application to manage to-do lists.
Chapter 4 introduces and explains a code design technique known as delegation.
This design pattern is used often in the Cocoa framework and is important to know
because it’s a core concept. You explore delegation by creating a web browser with
MacRuby.
Code conventions
There are many code examples throughout this book. These examples always appear
in a
fixed-width code font
. If we want you to pay special attention to a part of an
example, it appears in a
bolded code font
. Any class name or method within the
normal text of the book appears in code font as well.
Many of Cocoa’s methods have exceptionally long and verbose names. Because of
this, line-continuation markers (
➥
) may be included in code listings when necessary.
Not all code examples in this book are complete. Often we show only a method or
two from a class to focus on a particular topic. Complete source code for the applica-
tions found throughout the book can be downloaded from the publisher's website at
www.manning.com/MacRubyinAction.
Software requirements
An Intel-based Macintosh running OS X 10.6 or higher is required to develop Mac-
Ruby applications. You also need to download MacRuby, but it’s freely available at
http://macruby.org.
The book offers full coverage of MacRuby and Xcode 4.
Author Online
Purchase of MacRuby in Action includes free access to a private web forum run by Man-
ning Publications where you can make comments about the book, ask technical ques-
tions, and receive help from the authors and from other users. To access the forum
and subscribe to it, point your web browser to www.manning.com/MacRubyinAction.
This page provides information on how to get on the forum once you’re registered,
what kind of help is available, and the rules of conduct on the forum.
xx
about the cover illustration
The figure on the cover of MacRuby in Action is captioned “A man from Ubli, Dalma-
tia.” The illustration is taken from a reproduction of an album of Croatian traditional
costumes from the mid-nineteenth century by Nikola Arsenovic, published by the Eth-
nographic Museum in Split, Croatia, in 2003. The illustrations were obtained from a
helpful librarian at the Ethnographic Museum in Split, itself situated in the Roman
core of the medieval center of the town: the ruins of Emperor Diocletian’s retirement
palace from around AD 304. The book includes finely colored illustrations of figures
from different regions of Croatia, accompanied by descriptions of the costumes and
of everyday life.
Ubli is a town on the island of Lastovo, one of a number of small islands in the
Adriatic off the western coast of Croatia. The figure on the cover wears blue woolen
trousers and a white linen shirt, over which he dons a blue vest and black jacket, richly
trimmed with the colorful embroidery typical for this region. A red turban and color-
ful socks complete the costume. The man is also holding a pistol and has a short
sword tucked under his belt.
Dress codes and lifestyles have changed over the last 200 years, and the diversity by
region, so rich at the time, has faded away. It’s now hard to tell apart the inhabitants of
different continents, let alone of different hamlets or towns separated by only a few
miles. Perhaps we have traded cultural diversity for a more varied personal life—
certainly for a more varied and fast-paced technological life.
Manning celebrates the inventiveness and initiative of the computer business with
book covers based on the rich diversity of regional life of two centuries ago, brought
back to life by illustrations from old books and collections like this one.
www.it-ebooks.info
Part 1
Starting with MacRuby
MacRuby is a combination of technologies that together create a power-
ful and very usable new technology. Part 1 of this book provides the basics
MacRuby syntax and methods
■
Developing with the Xcode IDE
www.it-ebooks.info
4 CHAPTER 1 Introducing MacRuby
1.1 Introducing MacRuby
MacRuby is an Apple-sponsored development project. Over the years, Apple has
shown support for Ruby as a language, and, since 2002, Apple has included Ruby as
part of the
Mac OS X operating system. Apple bundled a Ruby Scripting Bridge imple-
mentation called RubyCocoa with Mac OS X Leopard. Prior to MacRuby, RubyCocoa
was the only way to work with Ruby and the Cocoa framework together.
In this section, you’ll learn how MacRuby is different from past attempts at com-
bining Ruby and Objective-C and what makes it such a great language. We’ll also jump
right into getting MacRuby installed onto your system and introduce you to Mac-
Ruby’s class structure.
Let’s set the stage for MacRuby.
1.1.1 The MacRuby difference
The goal of MacRuby is to provide an implementation of the Ruby language on top of
core Mac OS X technologies, such as the Objective-C runtime, garbage collection, and
Core Foundation. In MacRuby, all classes are Objective-C classes, all methods are
Objective-C methods, and all objects are Objective-C objects. Unlike RubyCocoa, you
don’t need a bridge between Ruby, Objective-C, and the Cocoa framework. MacRuby
is implemented on top of the Objective-C runtime as shown in figure 1.1.
MacRuby gives you the ability to do almost any-
thing you want with the Mac platform—all while giv-
ing you the clean, concise syntax of the Ruby
language. Another thing that sets it apart from
RubyCocoa is that you get this functionality without
making performance sacrifices because MacRuby