Beginning Mac Programming

Similar documents
Cocoa Programming A Quick-Start Guide for Developers

iphone SDK Development

Copyright 2009 The Pragmatic Programmers, LLC.

Web Design for Developers A Programmer s Guide to Design Tools and Techniques

Web Design for Developers A Programmer s Guide to Design Tools and Techniques

ios 9 SDK Development

Practical Programming, Third Edition

Build Database Apps in Elixir for Scalability and Performance

Java By Comparison. Extracted from: Become a Java Craftsman in 70 Examples. The Pragmatic Bookshelf

Java by Comparison. Extracted from: Become a Java Craftsman in 70 Examples. The Pragmatic Bookshelf

Developing Android on Android

Pragmatic Guide to Git

Modern Vim. Extracted from: Craft Your Development Environment with Vim 8 and Neovim. The Pragmatic Bookshelf

Automate with Grunt. Extracted from: The Build Tool for JavaScript. The Pragmatic Bookshelf

Reactive Programming with RxJS 5

Programming Clojure. Extracted from: Second Edition. The Pragmatic Bookshelf

Distributed and Parallel Computing with Ruby

Pragmatic Guide to Sass

Practical Programming, 2nd Edition

Agile Web Development with Rails 5.1

Practical Vim, Second Edition

Build Safe and Maintainable Front-End Applications

Build Reactive Websites with RxJS

Pragmatic Guide to Sass 3

Agile Web Development with Rails 5

Node.js 8 the Right Way

Practical Vim, Second Edition

My First Cocoa Program

Reactive Programming with RxJS

Build ios Games with Sprite Kit

Effective Testing with RSpec 3

SQL Antipatterns. Extracted from: Avoiding the Pitfalls of Database Programming. The Pragmatic Bookshelf

Copyright 2006The Pragmatic Programmers, LLC.

Complex Network Analysis in Python

Node.js the Right Way

Learn Functional Programming with Elixir

Deploying with JRuby 9k

Getting Started with Processing by Casey Reas and Ben Fry

CS193P: HelloPoly Walkthrough

Designed for Use Usable Interfaces for Applications and the Web

Agile Web Development with Rails 5

Copyright 2009 The Pragmatic Programmers, LLC.

My First iphone App. 1. Tutorial Overview

Dart for Hipsters. Extracted from: The Pragmatic Bookshelf

CS193E: Temperature Converter Walkthrough

Copyright 2010 The Pragmatic Programmers, LLC.

Programming Google Glass, Second Edition

Programming Clojure, Third Edition

ios 8 SDK Development

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Objectives. Submission. Register for an Apple account. Notes on Saving Projects. Xcode Shortcuts. CprE 388 Lab 1: Introduction to Xcode

1 Build Your First App. The way to get started is to quit talking and begin doing. Walt Disney

S A M P L E C H A P T E R

Windows XP. A Quick Tour of Windows XP Features

How to Make a Book Interior File

Design It! Extracted from: From Programmer to Software Architect. The Pragmatic Bookshelf

The kits are only available online. Participants will have access to their Course Kit 45 days prior to the course.

Trash in the Dock. May 21, 2017, Beginners SIG The Dock (Part 3 of 3)

iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5

Your . A setup guide. Last updated March 7, Kingsford Avenue, Glasgow G44 3EU

Registering for the Apple Developer Program

Your First Windows Form

Lesson 5: LDR Control

Learn to make desktop LE

Object-Oriented Programming in Objective-C

the NXT-G programming environment

Touring the Mac S e s s i o n 4 : S A V E, P R I N T, C L O S E & Q U I T

CLEARVIEW KIT INSTALLATION GUIDE

Creating An Account With Outlook

MAC BASICS. 125 S. Prospect Avenue, Elmhurst, IL (630) elmhurstpubliclibrary.org. Start Using Computers, Tablets, and Internet

Chapter 2 The SAS Environment

Interface. 2. Interface Adobe InDesign CS2 H O T

CHAPTER 1 COPYRIGHTED MATERIAL. Finding Your Way in the Inventor Interface

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Organizing Screens with Mission Control

NoteList 3.3 User Guide

Part 1: Understanding Windows XP Basics

Touring the Mac. S e s s i o n 1 : G e t t i n g Familiar With The Mac

PowerPoint for Art History Presentations

Arduino IDE Friday, 26 October 2018

The original image. Let s get started! The final result.

Xchange for Samsung MAC User Guide. Version 2.4

Learn to make watchosle

My First iphone App (for Xcode version 6.4)

Designing the staging area contents

Section 1. System Technologies and Implications. Modules. Introduction to computers. File management. ICT in perspective. Extended software concepts

Interactive Tourist Map

Barnes & Noble NOOK Study BLTI Tool for Sakai Admin & User Guide for version Sakai 2.7 v1.0.0 May 2011

Student Success Guide

Programming Kotlin. Extracted from: Creating Elegant, Expressive, and Performant JVM and Android Applications. The Pragmatic Bookshelf

SchoolMessenger App. Teacher User Guide - Web. West Corporation. 100 Enterprise Way, Suite A-300. Scotts Valley, CA

Photoshop Fundamentals

Structuring an App Copyright 2013 Apple Inc. All Rights Reserved.

Have the students look at the editor on their computers. Refer to overhead projector as necessary.

4Sight for Mac User Guide. Version 2.4

Basic Computer and Mouse Skills Windows 10

ITP 342 Mobile App Dev. Interface Builder in Xcode

Mac OSX Basics. Spring 2014

Lecture (01) Getting started. Dr. Ahmed ElShafee

Smoother Graphics Taking Control of Painting the Screen

Transcription:

Extracted from: Beginning Mac Programming Develop with Objective-C and Cocoa This PDF file contains pages extracted from Beginning Mac Programming, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit http://www.pragprog.com. Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printer versions; the content is otherwise identical. Copyright 2009 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent 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 this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at http://www.pragprog.com Copyright 2010 Tim Isted. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-10: 1-934356-51-4 ISBN-13: 978-1-934356-51-7 Printed on acid-free paper. P1.0 printing, March 2010 Version: 2010-5-16

THE TARGET-ACTION MECHANISM 61 Figure 4.1: The Go to Counterpart quick-switch icon in Xcode For now, we ll just output a message to Xcode s debugger console to let us know when this method is called, so add the following line of code: - (void)displaysometext { NSLog(@"displaySomeText just got called!"); } If you Build & Run at this point, you ll find that TextApp launches fine, but no friendly messages appear in the debugger console. We removed the code responding to the init message earlier, and at the moment our new displaysometext method never gets called. All we ve done so far is define the code that would be called if the displaysometext message was received, but it never is. 4.2 The Target-Action Mechanism Our aim is to send the displaysometext message to our NotifyingClass object when the user clicks a button in our TextApp application. The

THE TARGET-ACTION MECHANISM 62 Cocoa framework provides us with a nifty little technique to help with this, called target-action. Certain objects offered by the Cocoa framework allow you to provide them with a target object and specify an action a message to be sent to that object. One of the objects supporting such a mechanism is an NSButton. This class is used to create a number of different types of Mac OS X buttons; its default style is the one we ll be using shortly when we add a button to TextApp s user interface. Once we ve created an NSButton instance in Interface Builder, we can tell the button about our NotifyingClass instance and specify that the relevant action is to call its displaysometext method when the user clicks the button. At this point we need to make a couple of small changes to our existing method definition for displaysometext so we can use it with Interface Builder and target-action. For Cocoa desktop applications on the Mac, a method to be called in a target-action situation needs to conform to a specific signature format. The method needs to be able to accept a single argument on it. We ll discuss arguments in Chapter 6, Passing Information Around, on page 99, but if you take a quick look back now to earlier in this chapter at the format for a message signature, you ll see that there are optional bits that can be put on the end of the signature style we ve seen so far, as in one example from NSObject.h: + (id)allocwithzone:(nszone *)zone; If a message name has a colon on the end of it (that s : rather than the end-of-line semicolon ;), it means that it accepts one or more arguments. An argument is used to pass some information along with a message. Back in our housing example, when the property developer object sends a message to the builder object to buildhouse:, it needs to specify which house to build. This would be offered as an argument, like this: - (void)buildhouse:(house *)housetobebuilt; After the colon comes something in parentheses with an asterisk (House *) that specifies what kind of information is being provided, followed by a name to be assigned to the provided information. Don t worry if this isn t immediately clear in your head; we ll be covering various things in the next chapter that will help you to understand it. We ll continue using it in this chapter, though, so at this point, just follow along with the syntax.

THE TARGET-ACTION MECHANISM 63 + (id) allocwithzone:(nszone *) zone; - (void) buildhouse: (House *) housetobebuilt; ± («type expected in return»)methodname:(«type of info provided»)«name for info»; The buildhouse: method (notice we re putting the colon on the end of it to indicate it accepts an argument) expects to receive a House object when it s called, identifying the particular house to be built. Similarly, the allocwithzone: method expects an NSZone object to identify the zone to be used. Returning to target-action, I stated a little earlier that a method needs to accept a single argument to work for target-action. This argument happens to be used to identify the object that sent the message in the first place. When we connect a button in TextApp to target our NotifyingClass instance, the button would send the message and specify that it was the sender. The signature therefore needs to look something like this: - (void)displaysometext:(id)sender; The id keyword here is used to specify that some kind of object will be provided as the sender. Again, we ll be talking more about id later. There s just one last thing we need to change slightly on this method declaration, since we re going to be using Interface Builder to connect the target and action on a new NSButton object. Communication Between Xcode and Interface Builder Remember how we created an object instance in Interface Builder (that blue cube thing) in the previous chapter and set its class to Notifying- Class in the inspector? When we did that, Interface Builder managed to guess the rest of the class name after we d typed only a few characters. This is because Interface Builder and Xcode talk to each other behind the scenes. Some things happen automatically (like IB having knowledge of classes for which you ve provided class descriptions in an Xcode project), whereas other things happen when you use specific keywords in your code files. This is one case where we need to use such a keyword. To specify that our method is an action that can be connected to a control object (like an NSButton) in Interface Builder, we need to change the void keyword into IBAction: - (IBAction)displaySomeText:(id)sender;

THE TARGET-ACTION MECHANISM 64 As far as the code compiler is concerned, IBAction is synonymous with void. This keyword simply alerts Interface Builder that there s an action available in a class description. It s time to modify our code for this purpose. First, we need to change the interface for our NotifyingClass object, so open NotifyingClass.h in X- code. Change it so that the method follows our new action signature: @interface NotifyingClass : NSObject { } - (IBAction)displaySomeText:(id)sender; @end Next, we need to change our implementation method signature in NotifyingClass.m, so switch to this file, and make it look like this: @implementation NotifyingClass - (IBAction)displaySomeText:(id)sender { NSLog(@"displaySomeText just got called!"); } @end Notice that we don t need to do anything with the sender attribute we can quite safely ignore it altogether. And, since IBAction is just a keyword meaning void as far as the compiler is concerned, we don t have to worry about giving any information back at the end of the method. Make sure you save all your modifications before proceeding. If you hold down the E key on your keyboard and go to Xcode s File menu, you ll see that a few of the items have changed, and there is now a Save All... command (with keyboard shortcut E-D-S.) If there are any unsaved changes in any of the project s files, use this command to save them all at once. Connecting the Action in Interface Builder Now that we ve defined our NotifyingClass class instances to respond to an action message for displaysometext, we ll use Interface Builder to connect things visually. Let s start by adding a button to our existing TextApp window. Open MainMenu.xib, and make sure TextApp s Window object with the text view is visible.

THE TARGET-ACTION MECHANISM 65 Figure 4.2: The new push button in our Text App main window You will need to make that text view a little smaller by dragging up the bottom handle so there s room for a button underneath it. Next, find a standard Push Button object in the Library palette, and drag one out onto the window. You should end up with something resembling Figure 4.2. Next, remove one of the existing NotifyingClass instances from the Main- Menu.xib file by selecting it and pressing the J key. We re now ready to connect our button to the remaining NotifyingClass instance, and Interface Builder provides a great interface for doing this. Bring the MainMenu.xib document window to the front in Interface Builder, but keep the window with the button in it visible on screen. Right-click (or C-click) the Notifying Class blue cube. You ll find that a black mini-window pops up (known as a heads-up display, or HUD), as shown in Figure 4.3, on the following page.

SENDING MESSAGES FROM OUR CODE 66 Figure 4.3: The connections HUD for our NotifyingClass instance If everything has gone to plan, you should find that this HUD window shows one option under the heading Received Actions our displaysometext: action message. To the right of this line is a little circle; click and drag from the circle, and you ll find a line extends out and follows your movements on screen. Drag down to our new Button object, and you ll find IB highlights and identifies the button. Release your mouse, and you should find that the HUD display now shows a connection to our Push Button, as in Figure 4.4, on the next page. If you now bring the application s window to the front, click the push button to select it, and then right-click (or C-click) on it, you ll find that another HUD window will appear, showing a connection to our NotifyingClass object s action under the Sent Actions heading, as in Figure 4.5, on page 68. It really is as simple as that! Interface Builder has now set up our button with a reference to the notifying object and has set up the requested action for us, all with just a simple click-and-drag motion. Save your file in Interface Builder, and switch back to Xcode to Build & Run. TextApp will launch, and when you click the button in the window, you ll see a message appear each time in the Xcode console window. Woo-hoo! 4.3 Sending Messages from Our Code The target-action mechanism we explored in the previous section is awesome for connecting up buttons and receiving messages in certain situations, but we need to send messages to objects from our code too.

The Pragmatic Bookshelf The Pragmatic Bookshelf features books written by developers for developers. The titles continue the well-known Pragmatic Programmer style and continue to garner awards and rave reviews. As development gets more and more difficult, the Pragmatic Programmers will be there with more titles and products to help you stay on top of your game. Visit Us Online Beginning Mac Programming s Home Page http://pragprog.com/titles/tibmac Source code from this book, errata, and other resources. Come give us feedback, too! Register for Updates http://pragprog.com/updates Be notified when updates and new books become available. Join the Community http://pragprog.com/community Read our weblogs, join our online discussions, participate in our mailing list, interact with our wiki, and benefit from the experience of other Pragmatic Programmers. New and Noteworthy http://pragprog.com/news Check out the latest pragmatic developments, new titles and other offerings. Buy the Book If you liked this ebook, perhaps you d like to have a paper copy of the book. It s available for purchase at our store: pragprog.com/titles/tibmac. Contact Us Online Orders: www.pragprog.com/catalog Customer Service: support@pragprog.com Non-English Versions: translations@pragprog.com Pragmatic Teaching: academic@pragprog.com Author Proposals: proposals@pragprog.com Contact us: 1-800-699-PROG (+1 919 847 3884)