0% found this document useful (0 votes)
91 views28 pages

DDD - 0312 - April 2012

Uploaded by

Didi Mimi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views28 pages

DDD - 0312 - April 2012

Uploaded by

Didi Mimi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Mobile Development

Dr. Dobb’s Journal


Next

APRIL 2012
ALSO INSIDE

Writing Chrome Extensions >>

Fail-Safe Code? >>

7 Steps to a Killer From the Vault:


Displaying Tabular Data on iPhones >>

Mobile UI

www.drdobbs.com
Previous Next
More on DrDobbs.com
Mastering Threads on MacOS X
Dr. Dobb’s Journal The MacOS X platform has four thread solutions — two of
which are obsolete as of version 10.7. Your choices are now
POSIX threads or Cocoa’s NSThread class. Here’s how

CONTENTS April 2012


they compare and how to get up-to-speed on them quickly.
http://drdobbs.com/parallel/232602177

Looking for USB


Engineers hate reading directions almost as much as
they hate asking for directions.
http://drdobbs.com/blogs/embedded-systems/232602380

COVER STORY 18 From the Vault: Verdict on Visual Studio 11 Beta:


Not Ready for Prime Time
7 7 Steps to a Killer Mobile UI Concurrency Runtime (iPhone) — Despite the benefits of this new release, its unattractive
By Tiago Simões
The Task Scheduler UI and poor usability ruin the product.
Providing a good user experience in mobile applications is By Lahlali Issam http://drdobbs.com/windows/232602205
paramount. This article offers seven steps to get you on the Visual C++ 2010 came with new features and enhancements to
simplify native programming. The Concurrency Runtime Agile Success Factors
right path to delivering great mobile apps.
(iPhone), for instance, is a framework that simplifies parallel pro- Scott Ambler’s survey finds that at many sites, Agile ap-
gramming and helps you write robust, scalable, and responsive proaches work at scale, although it’s harder for them to
10 Writing Chrome Extensions parallel applications. This article explores the Task Scheduler, succeed at scale.
By Kausar Munshi and Basavaraju M which schedules and coordinates tasks at runtime. http://drdobbs.com/architecture-and-design/232601858
Extensions to Chrome enable you to extend the browser’s ca-
pabilities, change how pages are rendered, and interact with 3 Letters Creating a Custom Output Cache Provider in ASP.NET 4
the server in a controlled manner. For all their power, Chrome By you ASP.NET 4 provides support for cache extensibility through
extensions turn out to be comparatively simple to write and Readers weigh in on the VS 11 Beta, Flash, the JVM, and more. a provider model that you can write yourself. The primary
build once you know how. benefit of this approach is that you can cache objects out-
26 Links side of the ASP.NET Worker Process. Getting the perform-
Snapshots of the most interesting items on drdobbs.com in-
5 Guest Editorial cluding Cojac, CUDA-based plugins, and Android.
ance benefits of this customized cache control requires a
By Ron Wilson few basic steps, presented here.
http://drdobbs.com/windows/232601001
No tool or combination of tools can assure fail-safe code. 27 Editorial and Business Contacts
www.drdobbs.com April 2012 2
Previous
Previous Next
Next [LETTERS]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Mailbag
Chrome >>
iPhone >> Visual Studio 11 Beta, Flash appreciation, the JVM,
Letters >>
Links >> and CISC/RISC divide
Table of Contents >>

First Look at VS 11 lowed the creative development community to deploy a Flash player
for iDevices, developers would have continued on the path of better,
In response to Andrew Binstock’s editorial
faster, cheaper for software. There is no reason to use a proprietary low-
(http://drdobbs.com/windows/232602205) expressing concern
level language like Objective-C, other than you have to. This sounds like
about the Visual Studio 11 beta release , we received:
the old IBM game that lead to their downfall. They were so big that
The title of the editorial caught my attention: "Verdict on Visual Studio
companies did what they demanded, until companies got smarter and
11 Beta: Not Ready for Prime Time." After reading the article, I thought
did what they wanted, taking advantage of the whole open platform
the title was misleading since the title doesn’t specify only the UI but
world. Companies might follow Apple, too, while they have the control-
implies a broader scope. Perhaps "Verdict on VS2011 Beta: Drab and
ling market share, but nothing lasts forever. Somebody, somewhere is
Ugly" instead.
working on the next new thing, and it is unlikely to require Objective-
— Ryan Van Slooten
C. I want better, faster, and cheaper for my software developers.
On Mobile Driving Language Adoption — Steve Wilfe
Denver, Colorado
In response to the editorial, “The Rise and Fall of Languages in
2011” (http://drdobbs.com/mobile/232400093), which con- The JVM as a Language Incubator
cluded that mobile development was largely driving recent lan-
guage adoption: In response to the editorial discussing the JVM as a fertile plat-
While hardware gets better, faster, and cheaper, application develop- form for the development of new languages
ment productivity is becoming more complicated, slower, and more ex- (http://drdobbs.com/jvm/232600846), and that these languages
pensive. There was a reason Adobe Flash was king. It was better, faster, tend to be entirely new efforts, better versions of Java, or simply
and cheaper for software development. Write it once, deploy it every- ports of other languages to the JVM :
where. That was until the Apple empire became so powerful that they I think that the category mappings in the article don’t really fit. For ex-
could force the end of efficient multiplatform development. If Apple al- ample, NetRexx is really just the JVM version of Rexx as far as I am
aware; wouldn’t it belong in the "ports" category? Additionally, Mirah,
www.drdobbs.com April 2012 3
Previous Next [LETTERS]

while heavily inspired by Ruby, is not trying to be another Ruby; so I’m 99% of the time and save on decode-time for every instruction. The
IN THIS ISSUE
curious as to why it would belong in the "ports" category. I think some original idea was that you could do away with microcode altogether
Guest Editorial >>
Mobile UI >>
people may quibble about whether or not Scala should be in the "bet- and deal with incompatibilities in the compilers…but it did not work-
Chrome >> ter Java" or "its own thing" category. out that way.
iPhone >> I think there is also one notable omission: Rhino — the JavaScript im- Is RISC/CISC a meaningful distinction? No: CISC processors have
Letters >> plementation for the JVM. It has been around for ages. It powers a fair enough transistors to dispense with microcode (if they wanted to) and
Links >>
Table of Contents >> bit of server-side JavaScript on the Web. Common uses include server RISC processors need complex instructions for multicore locking. The
side JavaScript processing for initial page hits. difference between an ARM and an Atom processor is more about
Other interesting omissions: Erjang, and Erlang port, and there are at circuit design than which processor allows a WORD load from an non-
least two versions of PHP ports for the JVM that I’ve heard of. Erlang WORD-aligned address.
has some unique features, and if it could be successfully married to all —Steve Channell
of the rocket science and investment that go into Hotspot, it could pro- To which Andrew Binstock responds: “I don’t disagree with the
duce something very powerful, however unlikely that may be. PHP is second part of your analysis; namely, that CISC vs. RISC is a distinction
worth noting if only for its ubiquity. of diminishing relevance. As to the first point, Intel was definitely do-
I hope you get to Clojure soon. There’s a lot more to it than in many ing RISC instructions at the time I mentioned. Here is the description
of the other languages mentioned in the article. written by Hennessy and Patterson (the fathers of RISC) in Computer
— Bill Robertson Architecture — A Quantitative Approach, 3rd Ed. (http://is.gd/qqitUh):
“The P6 [so, Pentium III — Ed.] translates each IA-32 instruction into a
CISC vs. RISC on Intel Processors series of micro-operations (uops) that are executed by the pipeline:
In response to a comment that appeared in this column on page the uops are similar to typical RISC instructions.” I didn’t and don’t
3 of the March issue, in which Andrew Binstock gave a rough claim that the MUL instruction was implemented in RISC, only that its
time frame for Intel’s adoption of RISC instructions in the inner- ability to execute in half a clock cycle occurred at the same time that
most CPU execution instruction, we received: Intel was using RISC instructions in its processors. I stand by that as-
The response in the “Mailbag” was well wide of the truth, and mis- sertion and all my attempts to find counter arguments suggest that
understands what the distinction between RISC and CISC is. To de- it is in fact correct.”
scribe a CISC MUL instruction as being converted to RISC shift/addi-
tion is to miss the point. CISC vs. RISC was not about circuit design, Have a correction or a thoughtful opinion on Dr. Dobb’s content?
but about reducing instruction decode time by reducing the number Let us know! Write to Andrew Binstock at alb@drdobbs.com. Let-
of instructions to the ones most commonly used. For example, in- ters chosen for publication may be edited for clarity and brevity.
stead of {8,16,32} bit versions of multiply, you reduce to the one used All letters become property of Dr. Dobb’s.

www.drdobbs.com April 2012 4


Previous
Previous Next
Next [GUEST EDITORIAL]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
iPhone >>
No Tool or Combination of Tools Can Assure
Letters >>
Links >>
Table of Contents >>
Fail-Safe Code
The government’s analysis of Toyota’s automotive code revealed errors and failures. But
despite extensive overlapping forms of testing and modeling, it could not prove or clear
the software as a contributor to unintended acceleration.
By Ron Wilson

L
ast year, the U.S. National Highway Traffic Safety ation in Toyota Vehicles” (www.nhtsa.gov/UA) could be a case study.
Administration (NHTSA ) released an enormous The NASA team applied static source-code analysis, formal logic
report on its investigation into unintended ac- model checking, and algorithm analysis through simulation. The report
celeration in Toyota cars. It all seems very familiar, states, “The team’s experience is that there is no single analysis tech-
if you remember the Audi 5000. New electronic nique today that can reliably intercept all vulnerabilities, but that it is
throttle control reaches the market. Reports of strongly recommended to deploy a range of different leading tools.”
failure emerge from a few users. The vendor de- For code analysis, the team used Coverity, CodeSonar, and Bell Labs’
nies any problem. A few engineers quietly report having reproduced Uno (http://spinroot.com/uno/) to identify “common coding defects
the problem. But an intensive publicly funded investigation finds and suspicious coding patterns.” They also used CodeSonar to com-
nothing. pare Toyota’s code against a Jet Propulsion Lab coding standard.
What makes this report particularly interesting is that the NHTSA For model checking, the team used open-source Spin (http://spin-
called in an evaluation team from the space agency, NASA, to do the root.com/spin/whatispin.html#A) and its companion tool Swarm
heavy lifting. And that team included a software evaluation group. (http://spinroot.com/swarm/). Here, the tale gets more interesting. To
While the hardware folks were shaking, baking, and irradiating cars and use a formal model checker, you first have to write formal models. The
car parts, the software team had at the Engine Controller Module code team decided to build models only for those software modules they
for the four-cylinder 2005 Camry — all 280K lines of ANSI C. The team’s believed could be culprits — so the formal analysis depended upon
report, included as part of the larger “Report on Unintended Acceler- human judgment of possible fault modes.
www.drdobbs.com April 2012 5
Previous Next [GUEST EDITORIAL ]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >> The algorithm analysis started with — once again — building mod-
Chrome >> els, this time in Matlab. That process was undertaken by reading Toyota
iPhone >>
Letters >> documentation and talking with Toyota engineers. It then progressed
Links >> to analyzing the source code, and finally testing the models against
Table of Contents >> actual Camrys. Once the NASA team was satisfied with the models,
they explored failure scenarios in Simulink and checked delays with
AbsInt aiT.
Instantly Search
Some conclusions suggest themselves. First, there are no silver bul- Terabytes Of Text
lets: Effective debugging means using everything you’ve got. Second,
even when it’s grounded in exhaustive and formal techniques, an eval- • 25+ fielded & full-text search options
uation is circumscribed by the evaluators’ beliefs about the possible • dtSearch’s own file parsers highlight hits in
behavior of the system. Third, there is no certainty. Despite Toyota’s
popular file & email types
great care in developing their code, NASA’s analysis found significant
errors, including serious underestimates of delays in the multiprocess- • Spider supports static & dynamic data
ing system. But the investigation could not link those errors to any pro-
posed mechanism for unintended acceleration. Contrary to what you
• APIs for .NET, Java, C++, SQL, etc.
probably read in the papers, the NASA Executive Summary stated, “Be- • Win / Linux (64-bit & 32-bit)
cause proof that the ETCS-I [that is, the Electronic Throttle Control —
Ed.] caused the reported UAs [unintended accelerations] was not “Lightning Fast” – Redmond Mag
found does not mean it could not occur.”
“Covers all data sources” – eWeek
“Returns results in less than a second”
— Ron Wilson is the guest Editorial director of Embedded.com, EDN, and the Design-
lines at UBM Electronics. This is a slightly revised version of this article, which first ap-
– InfoWorld
peared in EETimes.
www.dtSearch.com
Comment Fully-Functional Evaluations
www.drdobbs.com April 2012 6
Previous Next [COVER STORY]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
iPhone >>
Letters >>
Links >>
Table of Contents >>
7 Steps To
A Killer Mobile UI
Here's how to write a successful mobile app
By Tiago Simões

O
dds are, you have a smartphone and without realizing it, 1. Define Your Goals
have developed a special, personal relationship with it. We What are you trying to accomplish with the mobile app? Most impor-
only recently learned that Steve Jobs charged the team he tantly, what will your users want from it? You must define the goals
assembled to create the first iPhone to “Create a phone that your app will address. For this, you need to understand the day-to-day
people will fall in love with.” Whether we admit it or not, all of us have activities of your users related to this app, and their goals and motiva-
a special connection with our iPhone, Blackberry, Android, or Windows tions around it.
Phone. A good technique is to create personas — fictitious characters that
But love is fickle. A recent Harris Interactive study revealed that bad represent your users — and write your specs as agile user stories. This
mobile apps can dramatically damage a brand’s reputation. Almost approach puts you in the correct mindset to state requirements for
one-third of respondents said they told others when they had a bad your app. Something like this: “As a security officer, Johnny Bravo must
experience with a mobile app. Still, more than half say they’ve recom- check-in using his mobile phone to find out the next checkpoint that
mended an app based on a positive experience. he should walk to so he can complete the randomized patrol tour.”
Providing a good user experience in mobile applications is para- This tactic lets you see the application from the user’s point of view.
mount. Here are seven steps to get you on the right path to delivering There are, of course, differences between user stories for mobile
great mobile apps. and desktop applications, particularly when considering the mobile
www.drdobbs.com April 2012 7
Previous Next MOBILE UI [COVER STORY]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >> context. For instance, a mobile user might be walking or using one ter suited for enter-
Chrome >> hand. prise applications. A
iPhone >>
Letters >> After gathering several of these stories, you must prioritize them ac- hybrid approach
Links >> cording to their frequency. I’ll explain why this is important shortly. makes sense if you
Table of Contents >> want mobile Web
2. Analyze Existing Apps apps easy mainte-
If it’s the first time you’re creating a mobile app, take a close look at nance but need
the interfaces of existing ones. Two obvious things stand out: The specific hardware
screen size is much smaller and since many mobile devices use touch capabilities, such as
An early Palm Pilot prototype side by side with the real thing.
screen, the elements on the screen must be larger, so they’re easy to the phone’s camera
touch. or GPS.
The smaller screen and the larger elements mean that you can only Taking advantage of existing frameworks and platforms can be a so-
put a limited number of items on the screen. lution, but whichever option you choose, make sure you can create
It can be a challenge to select what should go on the mobile screen; and modify the UIs quickly, and that you’ll be able to iterate often.
some usability experts even advocate that the mobile version of a
website be created before the desktop version. 4. Prototype Quickly
Prioritizing your user stories can help with this. You’ll want to take a A fast way to test a mobile interface at a project’s start is to use a low-
hard look at the features that your top priority users are using. Figuring fidelity prototype. Before the Palm Pilot’s launch, it’s said that the in-
out the 20% of the features that will be used 80% of the time is the ventor carried around a block of wood the size of the device to see
goal of every usability expert. If you do this correctly with mobile, the how it would feel in his pocket. Later, he’d have several rough versions
desktop will also have its priorities right. of the UI sketched on it.
Prototyping a mobile app is easy: A pencil and paper are all you need,
3. Native App or Mobile Web? and because screens are small, you will not have much to draw. Test
You’ll need to decide whether to use HTML5 or native APIs. This deci- your prototypes by asking users to try to accomplish tasks on them.
sion has more implications for the technical implementation than for See what they do, and ask them what they’re thinking. The results will
the user interface, however. Native apps usually run faster and are the be surprising and help you improve the design. A great design mantra
best option for games, offline, and hardware-intensive apps. Mobile is “Don’t Make Me Think!” If your mobile design fails this test, your app
Web apps are quicker to implement, easier to maintain, and often bet- will fail as well.
www.drdobbs.com April 2012 8
Previous Next MOBILE UI [COVER STORY]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >> 5. Avoid Errors That Ruin the UX you do this, remember to include a back button on your UIs, giving
Chrome >> When people start creating mobile applications, they typically make users an accessible exit option.
iPhone >>
Letters >> some known errors. First, if they’re creating the mobile version of an Remembering user selections across sessions (for example, a recent
Links >> existing website, developers often try to replicate every feature of the items list) is another smart touch that will make the app more context
Table of Contents >> desktop, failing to consider the intent of the mobile user. aware and free users from having to repeat navigation steps. Together,
Another common error is to have a navigation structure with too these usability quick-wins work to make the user’s life easier.
many levels. Deep structures aren’t well suited to mobile; simpler mod-
els work better. Expecting users to be able to easily input text is an- 7. Fail Early, Recover Fast
other mistake: Entering text is much harder on mobile devices, so you’ll Even with a good team of designers and developers, your first attempt
want to minimize the need for input. at creating a mobile app will likely fail. (A recent survey showed that
The applications that work best on mobile let users read content 38% of people are unsatisfied with the branded apps they tried.) The
more than write it. Think about it: Do any of your favorite mobile apps best strategy is to fail early and iterate quickly, learning how people
require you to enter a lot of text? are using your app and improving it continuously. Agile methodolo-
gies are a great way to align the mobile UIs you deliver with what users
6. Add Delightful Details need.
A mobile phone is always with you and knows where you are, which is Making the killer mobile UI is hard, but the strategies outlined in this
why mapping applications are so successful. Phones can hear what article will help. Follow them faithfully, and you’re on your way to writ-
you hear and see what you see, which explains the popularity of apps ing some great mobile apps!
like Shazam and Instagram. Using location, the camera, and the micro-
phone are all smart ways to get the same context as the user, and you
can take advantage of that context in unique ways. — Tiago Simões is a senior software engineer in the R&D group at OutSystems, a
Even if you aren’t using the mobile device hardware, there are several cloud-based application developer.
tricks you can use to delight users. Animations can add excitement to
your application. If you’re creating a mobile Web app, cache static con-
tent, and consider using a content delivery network so pages load
faster.
Another welcome touch for mobile Web apps is to let users add them
to their home screen, making them look and feel like a native app. If Comment
www.drdobbs.com April 2012 9
Previous Next [CHROME]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
iPhone >>
Letters >>
Links >>
Writing Chrome Extensions
Table of Contents >>
Extensions to Chrome enable you to extend the browser’s capabilities, change how pages are
rendered, and interact with the server in a controlled manner. For all their power, Chrome
extensions turn out to be comparatively simple to write and build once you know how.

By Kausar Munshi and Basavraju M

hrome Extensions are the code components used for • One or more JavaScript files (optional).

C adding new or enhanced features in the Chrome Web


browser. In other words, the functionality of the browser relies
substantially on add-ons or plugins to Chrome. In this article,
we explain what an extension consists of, how it can be developed,
• Any other files your extension needs — for example, image files
(optional).

Before going into the details of the extension’s components, let’s see
and then we provide a sample extension to illustrate the techniques. how to load and view an extension. Assuming you have all the exten-
sion-related files:
The Anatomy of Chrome Extensions
A Chrome extension is a zipped bundle of files — HTML, CSS, • Create a folder anywhere on your system to hold the above files..
JavaScript, images, and related extension files. Extensions are essen- • Go to the Extensions Management page in Chrome by clicking
tially Web pages, and they can use all the APIs that Chrome provides the wrench icon and choosing Tools > Extensions, and click on
to Web pages, from XMLHttpRequest to JSON to HTML5. Developer mode option.
A Chrome extension comprises the following files: • Use the Load unpacked extension button and specify the exten-
sion folder. This step will load the extension.
• A manifest file (mandatory). • If the extension is valid, its icon appears next to the address bar,
• One or more HTML files (mandatory) such as background.html, and information about the extension appears in the extensions
popup.html. page.
www.drdobbs.com April 2012 10
Previous Next [CHROME]

IN THIS ISSUE
Guest Editorial >> The extension is now ready to be used. Clicking on the extension’s "matches": ["<all_urls>"],
Mobile UI >> "js": ["page.js"]
icon (next to the address bar) enables interaction with the extension. }
Chrome >>
iPhone >> Note that this page provides options to Reload/Uninstall options for
"icons" : {
Letters >> the extension. Now, we’ll examine the contents of the extensions. "48": "a_48.jpg",
Links >> "128": "a_128.jpg"
Table of Contents >>
The Manifest File }
The manifest file, called “manifest.json,” provides information about
the extension such as the most important files and the capabilities that The manifest file is the heart of the Chrome extension. It contains
the extension uses. several name-value pairs specifying what functions are to be per-
If you’re not familiar with JSON , it stands for JavaScript Object No- formed by whom. The attribute’s name, version and description are
tation, and it’s a lightweight text-based open standard designed for metadata for the extension, whereas the attribute’s
human-readable data interchange in JavaScript. In this way, it serves background_page, options_page, and content-scripts give in-
as an alternative to XML. It is used for representing simple data struc- formation about the files that will be holding the corresponding logic
tures and associative arrays, called objects. It is language-indepen- (which will be described later).
dent, with parsers available for most languages. JSON files are de- The browser_action attribute, which is a composite JSON object
noted by the extension “.json.” JSON is often used for serializing and (that is, made up of one or more JSON objects), is a way of specifying
transmitting structured data over a network connection. Here’s a typ- the user interface (UI) to the extension. It holds the details of the image
ical manifest file: button or the UI that will be provided to the user to access the exten-
sion: It has the child attribute default_icon that specifies the icon to
manifest.json be used next to the URL in the address bar; and the child attribute
{
"name": "Kz_FACE_LIFT", popup contains the name of the HTML file that will be displayed when
"version": "1.1", you click on the icon in the address bar.
"description": "Kz FACE_LIFT PLUG-IN.",
"background_page": "background.html", The composite attribute icons specify the images that are to be dis-
"options_page": "options.html", played at various places. The child attribute 48 specifies the image/icon
"browser_action": {
"default_icon": "images/clock.png", that is to be displayed during the installation and uninstallation
"popup": "popup.html" process of the extension. The child attribute 128 specifies the
}, image/icon that is to be displayed in the chrome://extensions page
"content_scripts": [ where details of all the installed extensions are listed. The child attrib-
{ ute 16 has the same functionality as the default_icon attribute.
www.drdobbs.com April 2012 11
Previous Next [CHROME]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >> Extensions get the user interface in the following two ways: plays it on click. The manifest.json file specifies which HTML file will
Chrome >> hold the background processing logic. It does this via the attribute
iPhone >>
Letters >> • Browser action: An extension that enhances the functionality of background_page.
Links >> the browser irrespective of the pages. As long as the browser is A sample background.html is shown here:
Table of Contents >> running, the extension will be there. It adds an action item to the
<html>
browser. The action item is added in the browser’s toolbar in the <body>
aforementioned sample manifest file. <script src="script.js"></script>
<script type="text/javascript">
• Page action: An extension that enhances the functionality of the chrome.tabs.onSelectionChanged.addListener(myFun4);
browser depending on the Web page being visited. It will be ac- chrome.tabs.onUpdated.addListener(myFun4);
var val = 10 ; //declare a sample variable
tive as long as that page (or any page from that domain ) is open </script>
in the browser. It adds an action item to some of the pages that </body>
depends on the program logic. The action item is added in the
address bar for valid page addresses. Popup.html
Popup.html is basically a simple view that extracts data from back-
At most, an extension can have either one browser action or one ground pages or content scripts (which are JavaScript files) and dis-
page action. plays them. Thus, it provides a way of displaying the results of the op-
erations performed by the extension or the state of the extension.
Background.html In the manifest.json file, we describe which HTML file will act as the
The main logic of the extension resides in the background.html file. UI using the attribute popup. Note: There are many ways of displaying
When an extension needs to have a single long-running script to per- results to the user. We can use other HTML pages. The only difference
form some task, background pages are the solution. Although it is an is that we need to load those additional pages programmatically as
HTML file, its purpose is not used to add a GUI to the extension. Every- needed, whereas with popup.html, we do not need to write any logic
thing in this file is housed inside a <script> tag or contains a refer- for loading because it is attached with one of the standard Chrome
ence to a JavaScript file that holds the main logic. event “browser action/page action” extensions — whenever we click
This file exists for the lifetime of extension, and only one instance of the icon of the extension, popup.html will be displayed.
it per extension is active at a time. For extensions with only back- A sample popup.html is shown next, which just displays “Hello
ground work to do, the UI is implemented by dumb views. That is, the World” text when the extension icon is clicked ( it extracts data from
view collects any data from the background page as needed and dis- background.html):
www.drdobbs.com April 2012 12
Previous Next [CHROME]

IN THIS ISSUE
Guest Editorial >> <body> be used as the content script using the composite attribute con-
Mobile UI >> <h1>Hello World</h1> tent_scripts. It consists of a child attribute named js that tells
<script>
Chrome >> var newwin = chrome.extension.getBackgroundPage(); which file acts as the content script. The child attribute matches, which
iPhone >> alert(newwin.val);//where val is a var declared in
Letters >> holds a regex-pattern/url-value, tells the extension on which domain
//the background page.
Links >> </script> names and URLs the content script is valid.
Table of Contents >> </body> A sample of content script file is shown next, along with the mes-
sage-passing method of interaction. It sends a request to the back-
The chrome.extension.getBackgroundPage() returns the win- ground.html page passing status=2 as data, and waits for response
dow object of the background page from which we can access all the through the handler in which it displays the counter value from the
variables of the background page that are in the window scope. response received.
There is also an alternative way for the extensions pages to interact.
var payload = {status: 2};
They can use message passing, as will be discussed in the section on chrome.extension.sendRequest(payload,
content scripts . function handler(response) {
var a = response.counter;
alert(a);
Options.html });
This file enables the user to customize the behavior of the extension.
The options page should be included in the manifest.json file. It pro- The background.html file shown next handles the above request
vides a link to the options page from the extensions management sent by the content script.
page at chrome://extensions. In the manifest.json file, you describe
function onRequest(request, sender, sendResponse)
which file will be used as the options page using the attribute op- {
tions_page. var num1 = request.status;
if (num1==2)
{
Content Scripts Num2=20;
A content script is a JavaScript file that executes in the context of a sendResponse({counter:Num2});
}
Web page that’s been loaded into the browser. Think of a content }
script as part of that loaded page, not as part of the extension it was //register this function
chrome.extension.onRequest.addListener(onRequest);
packaged with. It interacts with the Web pages visited by the browser.
It can also interact with the extension pages by exchanging messages When the background page receives the request, it sends a response
(message passing). In the manifest.json file, you describe which file will back if the value received is 2. In addition to the exchange of data with
www.drdobbs.com April 2012 13
Previous Next [CHROME]

IN THIS ISSUE the background page, the content scripts can do much more by ac- bookmarks idle
Guest Editorial >> cessing the data of the loaded Web page, such as the document object
browserAction management
Mobile UI >> and its properties, and also modify them as needed.
Chrome >> contextMenus omnibox
iPhone >> cookies pageAction
Letters >> Chrome API
Links >> In addition to having access to all the APIs that Web pages and apps extension proxy
Table of Contents >> can use, extensions can also use Chrome-only APIs (often called fileBrowserHandler tabs
chrome.* APIs) that allow tight integration with the browser. For ex- history types
ample, any extension or Web app can use the standard il8n windows
window.open() method to open a URL. But if you want to specify
which window that URL should be displayed in, your extension can Table 1: The supported Chrome-specific APIs.
use the Chrome-only chrome.tabs.create() method instead.
pleted all their work. Often, synchronous methods have a return type.
Content.js For example:
Table 1 lists the supported chrome.* APIs.
DOMWindow chrome.extension.getBackgroundPage()

Asynchronous vs. Synchronous Methods This method has no callback and a return type of DOMWindow — it
Most of the methods in the chrome.* APIs are asynchronous: They re- synchronously returns the background page and performs no other
turn control back to the browser/script without waiting for the opera- asynchronous work.
tion to finish and while the operation continues to happen in the
background. To get the outcome of an operation after it is complete, a Using a Callback
callback function is passed upfront to the method, which will be ex- To navigate the user’s currently selected tab to a new URL, the current
ecuted later (potentially much later), after the operation is complete. tab’s ID is acquired (using chrome.tabs.getSelected()) and then
Here’s an example of the signature for an asynchronous method: that tab is directed to the new URL using chrome.tabs.update(). A
synchronous getSelected() could be written as below:
chrome.tabs.create(object createProperties,
function callback)
var tab = chrome.tabs.getSeleceted(null); // WRONG
chrome.tabs.update(tab.id, {url:”http://abc.com”});
Few chrome.* methods are synchronous. Synchronous methods ……………………………
will not have a callback because they don’t return until they’ve com- // THIS CODE DOESN’T WORK

www.drdobbs.com April 2012 14


Previous Next [CHROME]

IN THIS ISSUE
Guest Editorial >> This approach fails because getSelected() is asynchronous. It re- Extension Origin
Mobile UI >> turns without waiting for its work to complete, and it doesn’t even return Each running extension exists within its own separate security origin.
Chrome >> a value (although some asynchronous methods do). getSelected(), Without requesting additional privileges, the extension can use XML-
iPhone >>
Letters >> or any method in general, is identified as asynchronous by the presence HttpRequest to get resources within its installation. For example, if
Links >> of the callback parameter in its signature. For example: an extension contains a text file “abc.txt,” the extension can retrieve
Table of Contents >> chrome.tabs.getSelected(integer windowId, function the file’s contents as shown in the following code.
callback).
var xmlUnameRequest = new XMLHttpRequest();
The following code shows how to define a callback function that var url = "/abc.txt";
gets the results from getSelected() (as a parameter named tab) xmlUnameRequest.open("GET", url, true);
xmlUnameRequest.onreadystatechange = handler;
and calls update(). xmlUnameRequest.send(null);
function handler(evtXHR){
chrome.tabs.getSeleceted(null, function(tab){ if (xmlhttp.readyState == 4&&xmlhttp.status == 200) {
chrome.tabs.update(tab.id, {url:”http://abc.com”}); alert(xmlhttp.responseText);
………………………………. }
}); else {
//THIS CODE WORKS FINE alert(“Error ”+xmlhttp.status);
}
The callback function specified to getSelected is called only after }
information about the currently selected tab is available, which is
sometime after getSelected() returns. Also note that although up- If the extension attempts to use a security origin other than itself, say
date() is asynchronous, this example doesn’t use its callback param- http://www.google.com, the browser disallows it unless the extension
eter, as we don’t do anything with the results of the update. has requested the appropriate cross-origin permissions.The same per-
mission can be made available to the extension by specifying those
Cross-Origin XMLHttpRequest host names in the manifest file as below.
Extensions can interact with the outside world using XMLHttpRe-
{
quest objects available in JavaScript. Unlike regular Web pages, which “name” : “Kz_Face_Lift”,
can use XMLHttpRequest to send and receive data from remote “permissions”:[
http://www.google.com/,
servers, but are limited by the same origin policy, extensions aren’t http://*/*,
limited this way. An extension can talk to remote servers outside of https://*/
]
its origin as long as it has requested cross-origin permissions in its }
definition.
www.drdobbs.com April 2012 15
Previous Next [CHROME]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >> A match pattern of http://*/* allows HTTP access to all reachable The .pem file must update the
Chrome >> domains. Match patterns are similar to content script match patterns, extension and upload the exten-
iPhone >>
Letters >> but any path information following the host is ignored. Access is sion to the Chrome Web Store. On
Links >> granted both by host and by scheme. If an extension wants both se- successful packaging of the ex-
Table of Contents >> cure and non-secure HTTP access to a given host or set of hosts, the tension, a dialog box is displayed
permissions must be declared separately with https and http as in providing the information regard- Figure 1: The dialog box confirming
successful packaging of an extension.
the aforementioned example. While using an XmlHttpRequest object ing the location of .crx and .pem
in the plugin pages, you can pass the destination URL files. (Figure 1.)
(http://www.mysite.com/getData) after ensuring the same was speci- Packaging also can be done at the command line by specifying the
fied in the manifest file. folder where the plugin resides; and upon successful packaging, the
same dialog box will pop up.
Packaging and Deployment
chrome.exe --pack-extension= C:\KzExtension\Kz_FaceLift
To deploy the extension, the contents of the folder can be packaged
into a special ZIP file that has a .crx suffix.
Hosting
1. Bring up the extensions management page by going to the fol- The Web server that hosts .crx files must use appropriate HTTP head-
lowing URL: chrome://extensions ers, so that end users can install the file onto their browsers by clicking
2. Go to Developer Mode and Click the pack extension button. A a link to it. Google Chrome considers a file to be installable if the file
dialog appears. has the content type application/x-chrome-extension or the file suffix
3. In the extension root directory field, specify the path to the ex- is .crx and both of the following are true: The file is not served with the
tension’s folder — for example, c:\myext. (Ignore the other field; HTTP header X-Content-Type-Options: nosniff option, and it is
you don’t specify a private key file the first time you package a served with one of these content types:
particular extension.) • empty string
4. Click OK. The packager creates two files: a .crx file, which is the • "text/plain"
actual extension that can be installed; and a .pem file, which con- • "application/octet-stream"
tains the private key. • "unknown/unknown"
5. The .crx file can be hosted on a Web server for the end users to • "application/unknown"
download onto their Chrome browsers. • "*/*"
www.drdobbs.com April 2012 16
Previous Next [CHROME]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >> The most common reason for failing to recognize an installable file http://code.google.com/chrome/extensions/api_index.html
Chrome >> is that the server sends the header XContent-Type-Options: nos- http://www.w3.org/TR/XMLHttpRequest/
iPhone >>
Letters >> niff. The second most common reason is that the server sends an
Links >> unknown content type — one that isn’t in the previous list. To fix an — Kausar Munshi works as a developer in Java and Web Technologies. Basavaraju grad-
Table of Contents >> HTTP header issue, either change the configuration of the server or try uated from IIT Madras and has approximately 15 years of experience in IT.
hosting the .crx file on another server.
With this introduction, you should be well on your way to building
fun and useful extensions to Chrome.

Useful References
http://code.google.com/chrome/extensions/getstarted.html
http://en.wikipedia.org/wiki/JSON Comment

www.drdobbs.com April 2012 17


Previous Next [IPHONE]

IN THIS ISSUE From the Vault


Guest Editorial >>
Mobile UI >>
Chrome >>
iPhone >>
Letters >>
Links >>
Displaying Tabular Data on iPhones
Table of Contents >> This handy article from last year tackles the big problem of handling lots of data on a small screen. — DDJ

By Tom Thompson

ne of the great challenges facing developers of business ticle consolidates this information and introduces you to UITable-

O apps that run on mobile handsets is the presentation of


tabular data in an area slightly larger than a business card.
Presenting sufficient data at a size that is conveniently
readable is a difficult task, which must be done correctly. Flub this as-
View and its related classes. In addition, I demonstrate how to use
these classes through two example iOS apps.

Table Terminology and Types


pect and no one will use the app, regardless of how good its other In the abstract, table data is presented as rows of content, and the rows
properties might be. can be formatted in a specific style. Exactly what constitutes a row and
Fortunately, Cocoa Touch, the object-oriented framework used in a column though is a looser concept on mobile devices than it is on
programming for Apple devices such as the iPhone, iPod Touch, and the desktop. An iOS table row is a horizontal strip of content drawn
iPad, provides classes that display data in a compact, tabular format. across the width of the screen. Rows are often referred to as cells, from
One of the classes, UITableView, helps arrange such data into a hier- the UITableViewCell class that implements them. The content of a
archic structure of lists, with each list presented as a table on the row can be a mix of text or graphics, and you can specify the row’s
screen. Other supporting classes and methods enable a user to navi- height in points. However, because a row spans the width of the
gate easily through these tables (screens) of information. The user can screen, a table displays only one column of information.
then quickly drill down through a complex data set to reach the de- Rows of related content can be grouped into sections. Sections are
sired information. delineated by a distinctive header strip that appears at the top of each
Because UITableView is good at managing and displaying informa- group and contains a title. An optional footer can appear below each
tion, it often serves as the workhorse in data-centric applications. Un- group; it also has a title. The titles can consist of strings or graphics.
fortunately, the information on using UITableView is scattered Like the cells, you can specify the height of headers and footers. The
throughout volumes of documentation in the Apple iOS SDK. This ar- entire table can also have its own optional header and footer.
www.drdobbs.com April 2012 18
Previous Next [IPHONE]

IN THIS ISSUE
Guest Editorial >> events (typically touches). I have discussed the UIView class and
Mobile UI >> shown how to use it in the Dr. Dobb’s article, “The iPhone Isn’t Easy”
Chrome >>
iPhone >> (http://drdobbs.com/mobile/224200243).
Letters >> I mention the UIView class here because UITableView and
Links >> Figure 1: Comparing plain and group-style tables in iOS.
UITableViewCell subclass it. Therefore, they inherit the ability to dis-
Table of Contents >>
iOS tables come in two styles: plain and grouped. For the plain style, play content and respond to touch events. However, these classes do
a table consists of section headers, followed by rows of content dis- not store data. They only display the data and enable the user to inter-
played as lists. For example, the Mailboxes screen of the iOS Mail app act with the app’s data repository (which is known as the data model).
demonstrates this style. For the grouped style, the sections occupy dis- UITableView is responsible for implementing a table’s layout and
tinct screen regions, with the header and footer content appearing certain behaviors. It uses cell objects (described next) to organize and
above and below them. The Settings app is an example of this style. display the data. As Figure 2 shows, UITableView also inherits from
Figure 1 shows these two table styles, and indicates the sections, UIScrollView, which allows the table to be scrolled. However, the
headers, and footers. Note that while the plain style does support foot- table can scroll vertically only.
ers, they are often not used.
When you first create a table, you specify its style, either directly in the
code or in Interface Builder. Once set, a table’s style cannot be changed.
Table rows (cells) have four predefined styles: default, style1, style2,
and subtitle. These styles vary slightly in the number of built-in text
fields they offer and whether an optional image is displayed. Different
cell styles can appear in a table, and a cell’s style can change on the
fly, as driven by user actions.
Cells can also be customized to present additional text labels or im-
ages, or present controls such as sliders, buttons, and switches. For ex-
ample, in Figure 1 the grouped table (right) has cells that contain a
switch and a segment control.

Table Classes
A key class for managing an iOS device screen is the UIView. It is re-
sponsible for painting content onto the screen and capturing user Figure 2: How the Cocoa Touch objects and protocols interact to lay out a table.

www.drdobbs.com April 2012 19


[IPHONE]
Previous Next

IN THIS ISSUE The UITableViewCell class is responsible for displaying a row and
Guest Editorial >> its content. This class serves as a template that clones as many in-
Mobile UI >>
Chrome >> stances of a cell as is required to make up a section. In this sense,
iPhone >> UITableViewCell functions similarly to a Java factory method. Each
Letters >> cell can have a different style and displays the information that it ref-
Links >>
Table of Contents >> erences in the data model. As mentioned earlier, a cell can display text,
images, or controls. Cells are complex objects with many built-in views,
including several content-specific views, a background view, and an
accessory view. Figure 3 illustrates this. The accessory view displays
controls or optional images that assist in navigating to another screen.
Figure 3: Some of the key views in a cell using the default style.
Table Protocols
In iOS parlance, a protocol defines method declarations and the de- appearance of headers and footers, modify a cell’s height, and specify
sired responses when these methods are invoked. It’s up to the de- a background color or image. All methods in this protocol are optional.
veloper to assign a delegate object that implements the protocol. An A UITableViewController class is a variant of the NUIViewCon-
Objective-C protocol therefore functions like a Java interface. The iOS troller class that’s designed to manage a table. It packages house-
runtime is made aware that a class is a delegate object by the addition keeping functions and provides the stub routines for the data source
of a suitable protocol declaration in the class’s header file. and delegate protocol methods into one convenient view controller
Tables use two protocols: UITableViewDataSource_Protocol, class. This design allows the table’s event handling, data display, data
and UITableViewDelegate_Protocol. The UITableViewData- updates, and custom behavior to be contained in one omnibus object.
Source_Protocol obtains information for UITableView about UITableViewController also performs duties such as loading the
table layout and how to supply data to it for display. For table layout, table’s data, flashing the scroll indicators, and clearing the selection
this protocol defines two required methods. The first, num- choice. It exposes a property, tableview, which allows access to the
berOfRowsInSection, queries the app about the number of rows table view’s elements and properties.
a section has. The second method, cellForRowAtIndexPath, re- A final class, NSIndexPath, which has little to do with tables but is
trieves a specific cell in the table so that it can be matched up to its crucial to their operation, describes a path to a node in a tree of arrays.
data source and the data displayed. Recall that tables are organized as a hierarchy of lists, where each list
The UITableViewDelegate_Protocol describes how the table be- corresponds to an array. For tables, an instance of NSIndexPath pro-
haves and its appearance. This protocol is employed to customize the vides the section and row information that references a specific cell,
www.drdobbs.com April 2012 20
[IPHONE]
Previous Next

IN THIS ISSUE and can be used to also reference its data. Many table view methods where you can add your own code and observe the behavior. Click
Guest Editorial >> described here use NSIndexPath instances as arguments, or they re- Choose, name the project TestTable or something similar, and click
Mobile UI >>
Chrome >> turn results as an NSIndexPath. Save. Xcode generates a basic iOS app template that you can build and
iPhone >> For more information on each class, consult the iOS SDK documen- run. All the app displays at this point is a blank screen, but that’s fine.
Letters >> tation (http://is.gd/4gUK4l). We’re going to add the table as we go, and if something breaks along
Links >>
Table of Contents >>
the way, we’ll know where.
Making a Simple Table Now choose File > New File. In the dialog, select Cocoa Touch class,
Let’s write some code. The first decision is whether to use a NUIView- and NUIViewController subclass for the file’s code template. Under
Controller to manage the instance of UITableView, or a UITable- the options, make sure that UITableViewController subclass is
ViewController. The NUIViewController choice gives you fine- checked, and that With XIB for user interface is unchecked. This choice
grained control over every aspect of the table’s appearance and directs Xcode to add a UITableViewController class to the app’s
operation. However, such flexibility comes at a price: You have to man- template. Since we aren’t including a nib file, we’ll use Interface Builder
age every detail of the table’s operation, such as assigning and imple- to add the UI elements later. Click Next, and name the subclass file
menting the protocol delegate objects. In contrast, UITableViewCon- something descriptive like Table.m. When you build the app this time,
troller manages a lot of these details for you because it assigns itself two errors appear.
as the delegate object for both protocols, and provides some house- These errors flag the data source delegate methods numberOf-
keeping routines. The tradeoff is that some flexibility in table design is SectionsInTableView and numberOfRowsInSection. Xcode has
lost because this class implements certain default behaviors. However, provided stub routines for these data source protocols in the code
I have used UITableViewControllers for data display and in many template, but it can only go so far: You must supply information
cases I was able to customize the tables’ appearance without too much about the table layout. As mentioned previously, num-
effort. Unless you require an extremely customized UI, I would recom- berOfRowsInSection is a required method that requests the
mend starting with a UITableViewController. The example apps number of rows in a section. Oddly, numberOfSectionsInTable-
use UITableViewController for table management, so that is the View, which asks for the number of sections in the table, is not.
class I’ll discuss. We’ll start out simply by presenting a list of existing However, if you fail to provide a value greater than zero for the sec-
Apple products. tion number, the app crashes. For simple tables, you can hard-code
From within Xcode, Apple’s IDE for writing and debugging Mac OS these values, but for greater flexibility their values should be de-
X and iOS apps, choose File > New Project. In the New Project window, rived from the app’s data model. That way when the data model
choose iPhone OS Application and Window-based Application for the changes, so do the tables. Leave these alone for now, since we need
template. These choices will generate a minimalist app framework to create some data to display.
www.drdobbs.com April 2012 21
Previous Next [IPHONE]

IN THIS ISSUE
Guest Editorial >>
Make a new file with Xcode, but this time specify an Objective-C table data arrays so that you can buffer and process sensor informa-
Mobile UI >> class. For the “Subclass of” option, choose NSObject. Name this file tion or download data over the air into them before displaying their
Chrome >> TableData.m. Create a data array productNames, and add data strings contents.
iPhone >> to it, similar to that in Listing One. Now go back to Table.m, uncomment the method viewDidLoad,
Letters >>
Links >> and add code to initialize an instance of TableData called products
Table of Contents >> Listing One and to invoke initProductNames . Edit numberOfSection-
// TableData.m for a plain table sInTableView to return a value of one, and numberOfRowsInSec-
#import "TableData.h" tion to return a count value for the number of elements in the pro-
ductNames array. See the example app project PlainTable for more
//
@implementation TableData detail. If all goes well, the app should build without errors and run.
@synthesize productNames; However, nothing appears on the screen.

-(void) initProductNames {
productNames = [[NSMutableArray alloc] Final Fixes for Data Display
initWithObjects:@"iPhone", @"iPhone 3G", There are reasons for the lack of data on-screen. First, we haven’t done
@"iPhone 3GS", @"iPhone 4", anything about the other required data source method, cellFor-
@"iPod classic", @"iPod nano", @"iPod shuffle",
RowAtIndexPath. Search for that method in Table.m and you’ll find
@"iPod touch",
@"Macbook", @"Macbook Pro", @"Macbook Air", it soon enough. It is mostly stub code, which is why the app builds and
@"iMac", @"Mac mini", @"Mac Pro", executes without errors. This method returns a reference to UITable-
@"Apple TV", @"iPad", nil]; ViewCell, which is the class responsible for creating and displaying a
}
cell. (Listing Two.)
-(void)dealloc {
[productNames release]; Listing Two
[super dealloc];
- (UITableViewCell *)tableView:(UITableView *)tableView
}
@end cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";


Be sure to add a declaration of productNames in the TableData.h
file and also for the function initProductNames. Since we’re working UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
with constant data, we could use an instance of NSArray rather than if (cell == nil) {
NSMutableArray. However, for a real app, you want to allocate mu- cell = [[[UITableViewCell alloc]
www.drdobbs.com April 2012 22
Previous Next [IPHONE]

initWithStyle:UITableViewCellStyleDefault class, then a declaration of an instance of it to the interface. Add a


IN THIS ISSUE reuseIdentifier:CellIdentifier] autorelease]; property declaration for an instance of Table, say, table, as well. It’s
Guest Editorial >> }
/* add these lines of code important to specify this property as an IBOutlet. This makes a ref-
Mobile UI >>
Chrome >> cell.textLabel.text = [products.productNames erence to the class appear in Interface Builder (IB). See the header
iPhone >> objectAtIndex:indexPath.row]; TestTableAppDelegate.h for the details.
Letters >> cell.accessoryType = UITableViewCellAccessoryNone;
Links >> */
Table of Contents >> return cell;
}
“The app delegate class generates the instance of the
For performance reasons, the code first attempts to load a cached
window automatically when it loads, so only one line of
instance of a cell and reuse it. Otherwise, it generates one. However,
this method lacks the means to retrieve and display data content. We’ll code is required”
add our own code to do that.
In cellForRowAtIndexPath, add these lines:
Go to the TestTableAppDelegate.m file and add a synthesize dec-
cell.textLabel.text = laration for table. Follow this with a statement that adds the table view
[products.productNames objectAtIndex:indexPath.row]; to the window:
cell.accessoryType = UITableViewCellAccessoryNone;
[window addSubview:table.view];
The first line uses the row index (provided by the supplied index-
Path parameter) to access the appropriate string in the product- The app delegate class generates the instance of the window auto-
Names array. The string is inserted into the cell’s textLabel field, which matically when it loads, so only the one line of code is required. And
then presents it in the content view of the cell. The second line of code now, we add a final step: have IB tie the table into the app’s UI.
suppresses the display of any image in the cell’s accessoryView. This In Xcode, double-click on the MainWindow.xib file to launch IB. In the
location is where you can add extra code to access and display content MainWindow.xib window, choose Tools > Library to display the library
such as optional image, text, or controls. of Cocoa Touch objects. Drag the Table View Controller icon from the
However, when you build and run the project again, a table still library window into MainWindow.xib. Be sure to position the Table View
doesn’t appear. The second reason is because we have not added Controller above the Window object, as this can affect the display hier-
and connected the table view controller to the app’s main window. archy. If you expand the Table View Controller, you’ll find the Table View.
Most of these changes are made to the AppDelegate class, which, Select the table view controller, and choose Tools > Identity Inspec-
following our example should be named TestTableAppDelegate. tor. The Identity Inspector appears. For the Class option, we want to
First go to the header file and add a class declaration for the Table specify our custom table view controller, so click on the menu and
www.drdobbs.com April 2012 23
Previous Next [IPHONE]

IN THIS ISSUE @synthesize productNamesDesktop;


Guest Editorial >> choose Table from the list. The name changes in the MainWindow.xib @synthesize productNamesSettop;
Mobile UI >> from Table View Controller to Table. Click on TestTable App Delegate @synthesize productNamesTablet;
Chrome >> @synthesize productSections;
object in this window and pick Tools > Connections Inspector. The Con-
iPhone >>
Letters >> nection Inspector appears. You’ll see your instance of table as an outlet. -(void) initProductNames {
Click and drag from the table connection to the Table object in Main- productNamesPhone = [[NSMutableArray alloc]
Links >>
initWithObjects:@"iPhone", @"iPhone 3G",
Table of Contents >> Window.xib. This action has just created the link between table and @"iPhone 3GS", @"iPhone 4", nil];
the app’s UI. Save your changes in IB, then build and run the app. Now productNamesPlayer = [[NSMutableArray alloc]
a list of Apple products appears. As you see, there are a lot of little de- initWithObjects: @"iPod classic", @"iPod nano",
@"iPod shuffle", @"iPod touch", nil];
tails to get right when presenting a table. However, now that you un- productNamesLaptop = [[NSMutableArray alloc]
derstand them, building subsequent tables should be much easier. initWithObjects:@"Macbook", @"Macbook Pro",
@"Macbook Air", nil];
The other thing to notice is that the code uses a delegate protocol, productNamesDesktop = [[NSMutableArray alloc]
willDisplayCell. This method allows you to modify a cell’s appear- initWithObjects:@"iMac", @"Mac mini", @"Mac Pro",
ance prior to its being displayed, and the code in the example app al- nil ];
productNamesSettop = [[NSMutableArray alloc]
ternates between two background colors to help the rows stand out. initWithObjects:@"Apple TV", nil];
productNamesTablet = [[NSMutableArray alloc]
Sectioning the Data initWithObjects:@"iPad", nil];
productSections = [[NSMutableArray alloc]
Now, let’s go to the next level and divide the content into sections. To initWithObjects:@"Phone", @"Player", @"Laptop",
do this, we’ll slice the product list into categories and make those into @"Desktop", @"Settop", @"Tablet", nil];
table sections. Modifying the existing Table object, as shown in Listing }
Three, easily does this. Note how the list has been broken into arrays, -(void)dealloc {
where each array contains the strings for a particular product family.
[productNamesPhone release];
Listing Three [productNamesPlayer release];
[productNamesLaptop release];
// Table.m for a sectioned table [productNamesDesktop release];
#import "TableData.h" [productNamesSettop release];
[productSections release];
@implementation TableData
[super dealloc];
@synthesize productNamesPhone;
@synthesize productNamesPlayer; }
@synthesize productNamesLaptop; @end
www.drdobbs.com April 2012 24
Previous Next [IPHONE]

IN THIS ISSUE
Guest Editorial >> Given the rearrangement of the data model, the code in cellFor-
Mobile UI >> RowAtIndexPath must be modified as well. The code to update the
Chrome >> cell’s text content becomes:
iPhone >>
Letters >> cell.textLabel.text = [[listOfRows
Links >> objectAtIndex:indexPath.section]
Table of Contents >> objectAtIndex:indexPath.row];
Finally, to improve on the display of rows in the table, we modify the
table view’s property separatorColor, making it a light gray. This is
done in the numberOfSectionsInTableView method because it is
called only once. Now, when the app is built and run, the screen dis-
plays the products, partitioned into their families.
These examples only scratch the surface of what’s possible with iOS
Table 1: Important classes. tables. Feel free to edit and tinker with the example apps. Try changing
the cell’s style. Or with IB, change the table’s property from plain to
In the table view controller’s viewDidLoad method, we define grouped and observe the results. Such experiments can help expand
another array, listOfRows. Into this array we pack the product your knowledge of how iOS table design is done.
family arrays. See the second example program, SectionTable, Table 1 lists important classes and where they’re described in the
for details. SDK documentation.
For the numberOfSectionsInTableView method, instead of a hard-
coded value of one, we now return the count of the product sections,
like so: — Tom Thompson is a proactive support engineer at Freescale Semiconductor and a
frequent contributor to Dr. Dobb’s.
return [products.productSections count];

The same is done for numberOfRowsInSection, except here we re-


turn the count of objects that represent the rows:
return [[listOfRows objectAtIndex:section] count];

The section parameter references the appropriate product array


within listOfRows.,
Comment

www.drdobbs.com April 2012 25


Previous
Previous Next
Next [LINKS]

IN THIS ISSUE
Guest Editorial >>
Mobile UI >>
Chrome >>
This Month on DrDobbs.com
iPhone >>
Letters >>
Links >> Interesting items posted on
Table of Contents >>
www.drdobbs.com over the past
month that you may have missed

PROJECT OF THE MONTH: COJAC, A NUMERICAL of those services that zips up your code, ships it off to a build server in
PROBLEM SNIFFER the cloud, and has your APK file waiting for download somewhere.
Cojac’s runtime analysis of code identifies risky arithmetical operations http://drdobbs.com/blogs/tools/232602118
both in Java bytecode and in native binaries.
http://drdobbs.com/testing/232601564 THE CASE AGAINST INT, PART 3: THE ADVANTAGES
AND PERILS OF UNSIGNED ARITHMETIC
HOT-RODDING WINDOWS AND LINUX APP Integers are often used for counting, and that counting is often
PERFORMANCE WITH CUDA-BASED PLUGINS better suited to unsigned than to signed arithmetic. To that end,
Adding GPU capabilities to existing Windows and Linux apps can C++ defines an unsigned integer type, size_t, that is well-suited
be done simply using plugins and the built-in support found in to storing array indices, or otherwise counting items that can fit in
CUDA. This easy form of dynamic loading enables CUDA to be used the computer’s memory.
selectively to hugely accelerate individual tasks within a larger ap- http://drdobbs.com/blogs/cpp/232602212
plication.
http://drdobbs.com/parallel/232601605 THE SHRINKING EXPANDING WORLD OF CI
Continuous integration is undergoing somewhat of a renaissance
ANDROID ON ANDROID as continuous delivery (and its sidekick, DevOps) begin to find adop-
Android Java IDE, AIDE for short, has been released on the Android Mar- tion in many enterprises. Simultaneously, the number of viable CI
ket and provides a fully native Android application development ex- packages is shrinking quickly.
perience, running entirely on an Android device. And no, this is not one http://drdobbs.com/architecture-and-design/232601132

www.drdobbs.com April 2012 26


INFORMATIONWEEK Jerry Johnson Mykolas Rambus
Previous Next ADVISORY BOARD CIO CEO
Pacific Northwest National Wealth-X
Dave Bent Laboratory
IN THIS ISSUE M.R. Rangaswami
Senior VP and CIO Kent Kushar Founder
United Stationers VP and CIO Sand Hill Group
Guest Editorial >> Andrew Binstock Editor in Chief, Dr. Dobb’s CONTRIBUTING EDITORS Robert Carter E.&J. Gallo Winery Manjit Singh
Mobile UI >> alb@drdobbs.com Scott Ambler Executive VP and CIO Carolyn LEclispe CDTon CIO
Chrome >> FedEx Director, E-Services Las Vegas Sands
Deirdre Blake Managing Editor, Dr. Dobb’s Mike Riley
iPhone >> Michael Cuddy California Office of the CIO
dblake@techweb.com Herb Sutter
VP and CIO
David Smoley
Letters >> Jason Aprilnard CIO
Amy Stephens Copyeditor, Dr. Dobb’s Toromont Industries Managing Director Flextronics
Links >> astephens@techweb.com DR DOBB’S Laurie Douglas Wells Fargo Securities Ralph J. Szygenda
Table of Contents >> UBM TECHWEB Senior CIO Randall Mott Former Group VP and CIO
Sean Coady Webmaster, Dr. Dobb’s 303 Second Street, Publix Super Markets
scoady@techweb.com Sr. Executive VP and CIO General Motors
Suite 900, South Tower Dan Drawbaugh Hewlett-Packard Peter Whatnell
J. D. Hildebrand Editor at Large, Dr. Dobb’s San Francisco, CA 94107 CIO Denis O’Leary CIO
jdhildebrand@drdobbs.com 1-415-947-6000 University of Pittsburgh Former Executive VP Sunoco
Medical Center Chase.com
Jon Erickson Editor in Chief Emeritus , Dr. Dobb’s

UBM TECHWEB David Berlind IntelligentEnterprise.com


Chief Content Officer, App Architecture
INFORMATIONWEEK Thomas Claburn Editor At Large ART/DESIGN Tony L. Uphoff CEO TechWeb, and Editor in Doug Henschen,
Rob Preston VP and Editor In Chief, Information- Security, search, Web applications Mary Ellen Forte Senior Art Director John Dennehy CFO Chief, TechWeb.com Editor in Chief
Week tclaburn@techweb.com 415-947-6820 mforte@techweb.com
Fritz Nelson VP and dhenschen@techweb.com
rpreston@techweb.com 516-562-5692 Paul McDougall Editor At Large Sek Leung Senior Designer
David Michael CIO
Software, IT services, outsourcing sleung@techweb.com Guest Editorial Director, NetworkComputing.com
John Foley Editor, InformationWeek pmcdougall@techweb.com Joseph Braue Sr. VP,
jpfoley@techweb.com 516-562-7189 InformationWeek Business Networking , Communica-
Light Reading
Marianne Kolbasuk McGee Senior Writer IT INFORMATIONWEEK ANALYTICS Technology Network, and tions, and Storage
Chris Murphy Editor, InformationWeek management and careers Communications Network
analytics.informationweek.com Executive Producer, Mike Fratto, Site Editor
cjmurphy@techweb.com 414-906-5331 mmcgee@techweb.com 508-697-0083
Art Wittmann VP and Director Scott Vaughan CMO TechWeb TV mfratto@techweb.com
Art Wittmann VP and Director, Analytics, Infor- J. Nicholas Hoover Senior Editor awittmann@techweb.com 408-416-3227
mationWeek Desktop software, Enterprise 2.0, Ed Grossman Executive PlugIntoTheCloud.com
awittmann@techweb.com 408-416-3227 collaboration Lorna Garey Executive Editor, Analytics Vice President, Information- UNITED BUSINESS Cloud Computing
nhoover@techweb.com 516-562-5032 lgarey@techweb.com 978-694-1681 Week Business Technology MEDIA LLC John Foley, Site Editor
Alexander Wolfe Editor In Chief, Information- Heather Vallis Managing Editor, Research
Week.com Andrew Conry-Murray New Products and Busi- Network Pat Nohilly Sr. VP, Strategic jpfoley@techweb.com
ness Editor hvallis@techweb.com 508-416-1101
awolfe@techweb.com 516-562-7821 John Ecke VP and Group Development InformationWeek SMB
Information and content management INFORMATIONWEEK.COM
acmurray@techweb.com 724-266-1310 Publisher, Financial and Business Administration Technology for Small
Stacey Peterson Executive Editor, Quality, Infor-
mationWeek speterson@techweb.com 516-562- Benjamin Tomkins Managing Editor Technology Network,
W. David Gardner News Writer btomkins@techweb.com 516-562-5336 Marie Myers Sr. VP, and Midsize Business
5933 Networking, telecom InformationWeek Manufacturing Benjamin Tomkins,
wdavidg@earthlink.net Roma Nowak Senior Director, Government, and
Lorna Garey Executive Editor, Analytics, Informa- Online Operations and Production Site Editor
tionWeek Antone Gonsalves News Writer rnowak@techweb.com 516-562-5274 InformationWeek INFORMATIONWEEK btomkins@techweb.com
lgarey@techweb.com 978-694-1681 Processors, PCs, servers
antoneg@pacbell.net Tom LaSusa Managing Editor,
Healthcare VIDEO Dr. Dobb’s
Stephanie Stahl Executive Editor, Information- Newsletters Martha Schwartz EVP,
Week Eric Zeman informationweek.com/tv Good Stuff for Serious
tlasusa@techweb.com
sstahl@techweb.com 703-266-6030 Mobile and Wireless Group Sales, Developers
eric@zemanmedia.com Jeanette Hafke Web Production Manager InformationWeek Business Fritz Nelson Executive
Andrew Binstock
Fritz Nelson VP and Guest Editorial Director jhafke@techweb.com
Technology Network Producer
fnelson@techweb.com 949-223-3608 Editor in Chief
CONTRIBUTORS Joy Culbertson Web Producer fnelson@techweb.com
Beth Rivera Senior VP, alb@drdobbs.com
David Berlind Chief Content Officer, TechWeb Michael Biddick mbiddick@nwc.com jculbertson@techweb.com
dberlind@techweb.com 978-462-5315 Michael A. Davis mdavis@nwc.com
Nevin Berger Senior Director, Human Resources INFORMATIONWEEK
Jonathan Feldman jfeldman@nwc.com
User Experience BUSINESS
Randy George rgeorge@nwc.com
nberger@techweb.com
Eric Lundquist VP and TECHNOLOGY
REPORTERS Michael Healey mhealey@nwc.com Guest Editorial Analyst, In-
Charles Babcock Editor At Large Steve Gilliard Senior Director, NETWORK
Web Development
formationWeek Business
Open source, infrastructure, virtualization EDITORS DarkReading.com
cbabcock@techweb.com 415-947-6133 sgilliard@techweb.com Technology Network
Jim Donahue Chief Copy Editor Security
jdonahue@techweb.com Copyright 2012 United Business
Media LLC. All rights reserved.
Tim Wilson, Site Editor
wilson@darkreading.com

www.drdobbs.com April 2012 27


Previous Next

IN THIS ISSUE
Business Contacts
Guest Editorial >>
Mobile UI >> DR. DOBB’S SALES CONTACTS—EAST Entire contents Copyright © UBM TECHWEB
Chrome >> Sales Director, Michele Hurabiell Midwest, South, Northeast U.S. and Eastern Canada 2012, Techweb/United Busi- Tony L. Uphoff CEO
iPhone >> (415) 378-3540, mhurabiell@techweb.com (Saskatchewan, Ontario, Quebec, New Brunswick) ness Media LLC, except where John Dennehy CFO
Letters >> District Manager, Jenny Hanna otherwise noted. No portion of David Michael CIO
Links >> (516) 562-5116, jhanna@techweb.com this publication may be repro- Joseph Braue Sr. VP, Light Reading
duced, stored, transmitted in Communications Network
Table of Contents >> INFORMATIONWEEK BUSINESS District Manager, Michael Greenhut
any form, including computer Scott Vaughan CMO
(516) 562-5044, mgreenhut@techweb.com
TECHNOLOGY NETWORK retrieval, without written per- Ed Grossman Executive Vice President, Information-
Account Manager, Cori Gordon Week Business Technology Network
CMO, Scott Vaughan mission from the publisher. All
(516) 562-5181, cgordon@techweb.com
(949) 223-3662, svaughan@techweb.com Rights Reserved. Articles ex- John Ecke VP and Group Publisher,
Inside Sales Manager East, Ray Capitelli Financial Technology Network, InformationWeek
EVP of Group Sales, press the opinion of the author Government, InformationWeek Healthcare
(212) 600-3045, rcapitelli@techweb.com
InformationWeek Business Technology Network, and are not necessarily the Martha Schwartz EVP, Group Sales,
Martha Schwartz Sales Assistant, Elyse Cowen opinion of the publisher. Pub- InformationWeek Business Technology Network
(212) 600-3015, mschwartz@techweb.com (212) 600-3051, ecowen@techweb.com lished by Techweb, United Beth Rivera Senior VP, Human Resources
Publisher’s Assistant, Esther Rodriguez Strategic Accounts Business Media, 303 Second David Berlind Chief Content Officer,
(949) 223-3656, erodriguez@techweb.com Street, Suite 900 South Tower, TechWeb, and Editor in Chief, TechWeb.com
District Manager, Mary Hyland
(516) 562-5120, mhyland@techweb.com San Francisco, CA 94107 USA Fritz Nelson VP, Editorial Director,
SALES CONTACTS—WEST InformationWeek Business Technology
Account Manager, Tara Bradeen
415-947-6000.
Western U.S. (Pacific and Mountain states) Network, and Executive Producer, TechWeb TV
and Western Canada (British Columbia, (212) 600-3387, tbradeen@techweb.com
Eric Lundquist VP and Editorial Analyst, Information-
Alberta) Account Manager, Jennifer Gambino Week Business Technology Network
Inside Sales Manager, Vesna Beso (516) 562-5651, jgambino@techweb.com
UNITED BUSINESS MEDIA LLC
(415) 947-6104, vbeso@techweb.com Sales Assistant, Kathleen Jurina Pat Nohilly Sr. VP, Strategic Development and Business
Strategic Accounts (212) 600-3170, kjurina@techweb.com Admin.
Dr. Dobb’s Marie Myers Sr. VP, Manufacturing
Account Director, Sandra Kupiec
(415) 947-6922, skupiec@techweb.com Sales Director, Michele Hurabiell
Sales Assistant, Matthew Cohen-Meyer (415) 378-3540, mhurabiell@techweb.com
(415) 947-6214, mmeyer@techweb.com

MARKETING AUDIENCE DEVELOPMENT


VP, Marketing, Winnie Ng-Schuchman Director, Karen McAleer
(516) 562-7833, kmcaleer@techweb.com
(631) 406-6507, wng@techweb.com
Marketing Manager, Monique Luttrell BUSINESS OFFICE
(949) 223-3609, mluttrell@techweb.com General Manager, Marian Dujmovits

Marketing Director, Angela Lee-Moll United Business Media LLC


(516) 562-5803, aleemoll@techweb.com 600 Community Drive
Manhasset, N.Y. 11030 (516) 562-5000
Director, Client Marketing, Michelle Somers Copyright 2012. All rights reserved.
(516) 562-7928, msomers@techweb.com

www.drdobbs.com April 2012 28

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy