Sequoia’s Jim Goetz: Shocking More Startups Are Not Building For The Enterprise

By Alex Williams, TechCrunchSeptember 12, 2012 at 06:18PM

IMG_0718

In a discussion on stage at TechCrunch Disrupt in San Francisco today, Sequoia Capital’s Jim Goetz said it is shocking that more startups are not focused on the enterprise.

It’s the notion of reinventing the IT stack that holds such opportunity, Goetz said. And it’s an opportunity for everyone in the Disrupt audience. Companies like Salesforce.com have helped pave the way with SaaS models that build revenues based on subscriptions.

“The business model is now a weapon for all of you,” Goetz said. “It allows you to disrupt legacy vendors. It makes it very difficult for them to compete.”

There is also a major tech shift happening in the market, Goetz said. You have Flash becoming important for the server. Virtualization is now standard in the enterprise. You have new architectures.

Startups in the enterprise space face a different dynamic. They have only one or two competitors, and they are usually legacy providers.

“It is almost blue ocean,” Goetz said.

Palo Alto Networks Founder Nir Zuk came on stage to join Goetz. He said it takes two years to build an enterprise product. It takes two months to build a consumer service.

“How can you be proud of that?” Zuk asked.

MyFitnessPal Calorie Counter – The Best Weight Loss App On The iPhone

By Dave LeClair, MakeUseOfSeptember 12, 2012 at 09:31PM

weight loss appsEveryone knows that losing weight is difficult. It requires a certain level of commitment that not everyone is prepared for. However, when you meet those weight loss goals, it is one of the most satisfying things in the world. I am currently on a diet, as I need to drop about 20 pounds. It is not fun, but seeing the results helps me stay motivated.

Of course, losing weight is easier with help. That is where the weight loss app Calorie Counter & Diet Tracker by MyFitnessPal comes into play. It allows you to keep track of everything you eat and all the exercise you do. It also has some awesome social features that help you lose weight with the help of your friends who may be suffering through the same thing. It has everything a dieter needs to lose weight as quickly as possible.  Best of all, it is available on the App Store  for the low cost of free.

Getting Started

To get started you will have to create a free account. This is how you will communicate with your friends and keep track of your data across multiple devices. Setting up your account will allow you to set your goals and enter all the important information about your current physique. The whole process should not take more than a few minutes.

weight loss apps

Once you enter everything, the weight loss app will tell you how many calories you should consume per day to meet your weight loss goal. You can edit this number with recommendations from a doctor, which I highly recommend doing. The app is not a doctor, and it does not know your body. To find out the optimal amount of calories, a doctor is the best option.

Logging Food

The main purpose of this app is keeping track of how much you eat and making sure to stay under a certain amount of calories. Thankfully, MyFitnessPal has the largest food database of any similar app, so finding your food should not be an issue.

iphone weight loss apps

You can manually type in what you ate or use the built in barcode scanner. Once you find the food, you simply enter in how much you ate, and the app will log it for you.

iphone weight loss apps

As you eat, the app will tell you how many more calories you have left for the day. You need to make good food choices to stay under your limit. I find it helpful to treat it like a game. It helps keep me motivated and helps me stay under the limit so the pounds keep coming off.

Logging Exercise

Keeping track of your exercise is just as important as keeping track of your food. The method for entering exercise is the same as food, except there is no barcode scanner. The database has a general idea of how many calories you will burn during a specific exercise, but for best results, you should look into a heart-rate monitor. This will give you a more accurate representation of how many calories you’ve burned.

iphone weight loss apps

When you exercise, you gain that many calories back in food. So for example, let’s say you are allowed 1,600 calories a day. If you go for a run and burn off 400 calories, you would be able to eat 2,000 calories that day and still meet your goal.

Other Features

MyFitnessPal is literally packed with features designed to help you lose weight. It has great social integration designed to help you meet goals with friends no matter where they are. You can also share important events on your Facebook for your other friends to see. Knowing that you can tell the world when you meet an important weight loss milestone is a great motivator for some people.

You can also store custom foods and meals. If there is a certain meal you tend to eat often, you can save the parts of that meal and add it with a single click. For example, if you eat a chicken breast, brown rice and broccoli all the time, you can save those as a meal and add them to your diary instantly instead of adding each part every time you have it. If a food is not in their database, which is unlikely, you can add it manually using the nutritional information on the package.

MyFitnessPal also synchronizes with their website, so you can always log new entries to your diary from a computer if you are not near your phone. The data will synchronize automatically as long as your iPhone has a data signal. If you do not have Internet, all the data will store locally until the next time you connect.

weight loss apps

One last cool feature is the reminders. You can tell MyFitnessPal to remind you to log your meals if you have not done so by a certain time each day.

Conclusion

MyFitnessPal is the best weight loss app I have ever used on the iPhone, and I have no problem recommending it to anyone who is trying to lose weight. It is easy to use, and has all the features you could ever want for dieting. Seriously, give it a shot if you need to drop a few pounds.

Have you tried Calorie Counter & Diet Tracker by MyFitnessPal? How did you like it? Let us know in the comments!


Secrets Of High-Traffic WordPress Blogs // Study

By Siobhan McKeown, Smashing Magazine FeedSeptember 12, 2012 at 10:05AM


  

We all know that WordPress is awesome — but being awesome isn’t always enough. Does it perform well under pressure? Can it deal with traffic from millions of visitors every month? There’s no question that WordPress can be used for your or my blog, but what about multi-author blogs with thousands of comments? How do developers make it scale and perform?

I spoke with the developers behind some of the biggest WordPress blogs on the planet and asked them to tell me their secrets. Now I get to share them with you.

The Blogs

Website Monthly uniques Monthly page views
Digital Trends 10 – 12 million 33 million
iPhoneclub.nl 2.5 million 5.4 million
The Next Web 4 million 8 million
Neatorama 2.5 million 4.5 million
Slashgear 6 million 10 million
Hot Air 2 – 3 million 35 – 45 million
Laughing Squid Undisclosed Undisclosed

In The Beginning

The first thing I asked the developers was whether they prepared for the heavy traffic that now flows through their website. In almost all cases, the answer was a resounding no. From The Next Web, CTO Arjen Schat and lead developer Pablo Roman said they had planned for growth but didn’t expect growth to happen on such a large scale. “There were few large WordPress sites at the time, so we learned as we went along.”

Neatorama started out in late 2005 on cheap shared hosting until it got kicked out. It moved to a VPS and got kicked out again. In 2007, it moved to a dedicated server with a CDN, which eventually was insufficient, until finally it moved onto load-balanced servers with a CDN. Similar stories are echoed by iPhoneClub.nl and Laughing Squid.

Hot Air’s developer, Mark Jaquith, also a lead developer at WordPress, had to migrate his website to a new server within 48 hours of launching. Only SlashGear planned for a 30% increase in traffic per year.

Digital Trends

Digital Trends started out with around a million uniques a month and has since risen to 10 to 12 million uniques. Tom Willmot, of Human Made, the development shop behind Digital Trends, said this of starting out:

When I started work on the website, there were some pretty big performance sinks in the code base that needed ironing out. A clean code base takes you only so far, however. I don’t think it’s something that should be too heavily focused on at the outset as you don’t know what specific features will need performance considerations. Coding well plus some persistent object caching are enough to begin with.

Server Shred And Burn

High-traffic blogs have to deal with things that regular bloggers only dream of: loads and loads of visitors, eager to read all of the latest news. Neatorama held up when it was featured on the front page of Digg, but was shredded within a few minutes of being featured on Yahoo’s front page — over 2 million visits in the space of a few hours. To deal with that, it had to make a static page on a CDN and redirect traffic there.

Other blogs face challenges related to major events. Visitors flock to their websites to follow what’s happening and hear the news. iPhoneClub.nl and SlashGear are particularly affected during Apple’s live broadcasts. SlashGear experiences traffic of more than 4 million uniques within the two hours of a broadcast’s duration; to deal with this, it adds Amazon EC2 to its normal infrastructure.

iPhoneclub.nl

Jean-Paul Horn, whose iPhoneclub.nl started out on WordPress 2.0.5, had to learn to deal with these problems on the fly:

We used to run a standard LAMP stack with WP Super-Cache, since the site was already growing rapidly when the iPhone started to get really popular. Our main problem was that the server ran perfectly fine on normal news days, but almost literally burned whenever Apple had a keynote or another big iPhone-related announcement. We tried preparing for these short avalanches by temporarily adding more cores and RAM, but it was never really enough, and I wasn’t really keen on investing in a big-ass server just for two to three days of insane amounts of Web traffic a year.

While moving to a Web server and database server with MySQL stored on a separate server helped in its continuing growth, it was still dealing with the same issues when Apple held a press conference. Enter Frederick Townes of W3 Total Cache and Mashable fame. Jean-Paul met Frederick at WordCamp Netherlands, and Frederick went on to help them set up their current configuration:

  • The app server hosts the Varnish front end.
  • They use two nginx Web servers: one with PHP-FRM, the other with static content, like a CDN.
  • The database server runs a highly tuned MySQL server, in which some of the WordPress tables, such as wp_posts, have been transitioned from MyISAM to InnoDB. Because InnoDEV doesn’t have full text search, Sphinx Search was implemented.

Jean-Paul has been using this configuration since November 2011 and has survived two major Apple events without any of the previous load issues or other performance troubles. They’ve also been able to accommodate more traffic and have beaten all of their previous traffic records.

Dealing With Growth

Hot Air

Hot Air

US political blog Hot Air has gone through some major performance and scaling sprints, particularly in advance of US election years. An election guarantees a larger than average flurry of activity around politics. Given that politics is already one of the most popular topics on the Internet, this means some hardcore scaling. Mark Jaquith explained to me the steps he has taken to cope with scaling:

  • Deliver all static assets through a CDN.
  • Set up a load balancer, with multiple Web back-ends behind it.
  • Cache the front page proactively
  • Cache page fragments (such as sidebars) proactively, so that they can be loaded statically.
  • Cache recent posts proactively (mostly the ones displayed on the home page). Every time a post is updated or a comment is left, a back-end process generates a new static snapshot of the page and distributes it to the Web machines.
  • Eliminate the cache differentiation between logged-in and anonymous viewers. Most caching plugins don’t cache pages for logged-in users, or if they do, they cache a different version for each viewer. Hot Air’s templates are modified so that there is no difference in the HTML generated for logged-in and anonymous users, so there can be one shared cache pool.
  • Use Batcache (with a Memcached object cache back end) to cache views of old content.

The Next Web

The Next Web

As with most of these other blogs, scaling was forced upon The Next Web. The founders did plan for growth, but not on the scale they encountered. Arjen and Pablo went into detail on how they dealt with it.

The team’s essential tools are:

  • Varnish as a reverse proxy and for ESI (Edge Side Includes);
  • Memcached to store the results of heavy queries, such as popular stories;
  • Munin for monitoring.

Setting this up wasn’t enough, though. All of this had to be tuned, and poorly performing plugins and code had to be identified. To do this, they did the following:

  • Use MySQL slow query log with no-index enabled.
    Keeping your MySQL slow logs empty is essential. Your key cache suddenly might not be sufficient anymore if your data is growing.
  • Use XHprof for code path analyses.
  • Keep Apache logs clean.
    External referrers will link to pages on your website that don’t exist anymore. If a WordPress 404 page is loaded every time, then you’re doing work that can be avoided. Generating a 404 page can be heavy, so it needs to be cacheable in Varnish as well.

The team at The Next Web also uses additional tools with Varnish to improve cache hit rate. These include:

  • varnishtop
    Lets you look into Varnish.
  • varnishtop -i txurl
    This shows you all of the requests that make it into Apache that aren’t cached by Varnish. This helps you to identify different cases:

    • Whether the back end sends a header that Varnish can’t cache;
    • Whether the back end starts a session that isn’t needed;
    • Partially malformed links to your website, such as https://thenextweb.com/apple/https://referrer.com/my/cool/article;
    • Small variations of a normal request that you can normalize in Varnish, so that you can serve the standard page, such as https://thenextweb.com/correct/article/link?utm=campaign.
  • WP-VCL
    Their basic VCL, which normalizes many different request into the standard versions.

An essential step for The Next Web was developing the ability to serve cached content to logged-in users. To do this, it pulls in all of the user-specific parts of the page and loads these through an AJAX call. This means that content doesn’t need to load all of WordPress. The developers have duplicated all of the code that is needed to handle logging in and basic user-profile stuff in WordPress into its own tiny login class. The class takes 1 millisecond to load, instead of 100 to 200 milliseconds to load through the whole WordPress stack. This prevents WordPress from loading for a trivial request, which can degrade the overall performance of your website by eating CPU cycles that should be used to render pages that are not cached. An added benefit is that WordPress can render all pages in non-logged-in mode.

This is used simultaneously as a feature of Varnish called ESI, which lets the team cache different sections of a page separately with different expiration times. This lets them show fresh content in the sidebar widgets even if the main content has a long expiration time.

Essential Plugins

Essential Tools And Services

Challenges

High Levels of Caching

All of the blog owners I spoke with have high levels of caching. Digital Trends deals with this by using Akamai Distributed, Varnish and Memcached. When this is combined with user log-ins and registrations, it can be difficult to make sure that everyone is seeing what they should be seeing while caching as many things as possible.

Mobile

iPhonclub.nl has to deal with a relatively high number of mobile visitors. In the past, it used WPTouch for iPhone visitors (along with its native app). The server team had to do major work with Varnish, nginx, and W3TC to keep the caches for desktop and mobile visitors separate, thus making user configuration more complex. However, later this year iPhoneclub.nl will merge with iPadclub.nl to become iCulture.nl. In addition to the merge, they are moving to a responsive design, which will better suit the new website and solve the issue of dealing with mobile visitors.

Built to Work, Not to Perform

A challenge raised by The Next Web is the actual architecture of WordPress. While using all of the options and all of the plugins is easy, they are built to work, not to perform. With every code change, you have to make sure it doesn’t cripple performance.

Security

Security is a big issue for every WordPress user, particularly for high-visibility websites. As Neatorama points out, keeping WordPress up to date isn’t always enough. You also have to keep your server’s operating system up to date as well.

Huge Servers
Some websites need a huge server. (Image: Skimaniac)

Scalability

Slashgear has found it challenging to scale WordPress without chucking more hardware at it. It uses a caching system, but WordPress is built to be dynamic, and caching in a dynamic environment does not always work smoothly. The developers have overcome this by modifying their plugins to use AJAX to pull live data on statically cached generated pages.

Comments

A website like Hot Air can receive hundreds or even thousands of comments for a single post. There are dozens of posts every day, and the website has been live for six years. “With that many comments,” says Mark, “you really have to look at database optimization. We have a few custom plugins that intercept comments queries and rewrite them to be simpler. And you want to limit the number of queries you make against that table. For instance, I killed the ‘Right Now’ and ‘Recent Comments’ sections of the Dashboard.”

Events

As discussed regarding iPhoneclub.nl and SlashGear, Hot Air has to deal with its own major events. When a big political event is happening, just a few minutes of downtime can do damage. Mark has warning systems and automated responses in place. In the event of an problem, he can set up something to automatically fix it if it recurs or to notify him when something indicates that a performance issue is imminent.

Would You Say Goodbye To WordPress?

I asked all of the blogs whether they’ve ever conceived of a situation in which they would have to move beyond WordPress. Here’s what they had to say.

Tom Willmot, Digital Trends

I really don’t like the whole “WordPress is slow” rhetoric. It’s just PHP plus MySQL — so is Facebook. It is possible to move beyond certain things that WordPress does (for example, perhaps you replace the rewrite engine with something more efficient), but to decide fundamentally that WordPress is somehow slow and needs to be gotten rid of is probably avoiding the specific issue that is the problem. Sure, there are aspects of WordPress that can be slow if you don’t do anything about them, but this is far outweighed by everything that you do get.

Writers love the WordPress back end; WordPress.com runs some of the largest websites in the world. Digital Trends servers 33 million pages a month for a website that is hugely more complicated (from a technical point) than a blog.

Jean-Paul Horn, iPhoneclub.nl

I can’t for the life of me think why I would want to do this. I have been using WordPress since early 2.0. My wife started iPhoneclub.nl in December 2006 on WordPress 2.0.5 and we haven’t looked back since. I had some previous experiences with PHP-Nuke and Joomla, but WordPress has really grown on me for its simplicity and huge developer community.

For almost every missing piece of functionality in core, a plugin is available or so easy to patch that you could write your own theme-specific function. I evaluated both Drupal and ExpressionEngine (then called pMachine) when we faced our performance issues, but stuck with WordPress because of its extensibility and there was already a clear vision laid out for WordPress becoming more of a full-featured CMS.

 

The Next Web

I don’t see a situation where you need to move beyond WordPress, as long as you don’t fall into the trap of thinking you can do everything with a plugin.

Laughing Squid

WordPress continues to evolve along with us and is still the best platform out there for blogging. There is every indication that it will continue to be so in the future.

SlashGear

[We would leave] when WordPress becomes too bloated. As you can see, each major WordPress version comes with more hooks (WordPress 3.0 had a little over 750 hooks, and 3.4 has over 1500 hooks). At this point, we prefer scalability and platform robustness over features that are not commonly used.

Mark Jaquith, Hot Air

No way. Comments are the hardest thing to scale, and there are solutions for that, such as using an external service or even sharing comments between multiple tables. I haven’t yet come across a problem that I didn’t think could be solved, and the flexibility and extensibility of WordPress have proved invaluable.

Saying Goodbye

Why would anyone ever want to leave WordPress? One of the blog owners I spoke with was in the process of doing just that. Neatorama’s e-commerce operation, NeatoShop, has grown, and it has decided to integrate the blog and the shop into one platform. This makes it possible for it to tailor its publishing process to fit its particular needs, such as scheduling and queueing multiple posts, maintaining multiple blogs with a single dashboard, cross-posting and having an inline commenting system. For Neatorama, the problem wasn’t WordPress itself, but that they couldn’t implement large-scale e-commerce.

Neatoshop

I asked Alex Santoso of Neatorama why he hadn’t considered using a WordPress e-commerce plugin such as WooCommerce or WP E-Commerce. Here’s what he had to say:

Because e-commerce isn’t just a shopping cart — there’s a whole other logistics fulfilment and shipping back end to it. We grew NeatoShop from selling just 12 t-shirts to over 5,000 items today, and we had to write our own software to enable us to process (i.e. ship) orders efficiently.

I’m doubtful that you can do large-scale e-commerce with plugins. Selling a dozen items or so should be no problem, but keeping track of thousands of items in inventory, minimizing fraud, automating, and the logistics would be.

It’s interesting that Neatorama feels that plugins aren’t sufficient to carry out large-scale e-commerce. But how does Alex feel about WordPress as a publishing platform?

We’re not moving away from WordPress because it’s failing us as a blogging platform. Rather, our business evolved from being a pure publisher into a side-by-side e-commerce and blogging operation. WordPress and its vibrant community continue to be a great choice for most publishers big and small.

Learning From The Pros

It’s great to hear about what all of these websites are doing, but what advice can they offer you?

Servers

Learn how to deal with servers, or get someone who does. You should know how to configure nginx and PHP-FPM, MySQL slaved with HyperDB, Varnish VCLs, and NFS. “If you don’t know how to deal with the stuff in between a browser sending the request and your code running,” warns Tom Willmot, “it will seriously limit you in terms of how things can be improved and also debugging issues. Server issues can be extremely frustrating; if you don’t have a handle on it, it will come back to bite you.”

Read and Learn

Jean Paul Horn advises that you should keep up with the latest performance recommendations, and he particularly recommends the following:

Ask for Help

“Don’t be afraid to ask for help,” says Jean Paul. “The community out there is exceptional and truly supportive.” Spend money hiring WordPress performance experts. This provides an excellent return on investment. If your website goes down or is unreachable, potential readers could end up with the competition. Trying to visit a website that is constantly down is frustrating for the visitor, and they won’t stick around.

Shop Around

Alex Santoso suggests that you “Shop around for hosting costs. Similar hardware configurations can have vastly different pricing from different hosting companies.”

Trail and Error

SlashGear suggests that you use trial and error to get your configuration right. Decide whether a plugin is really necessary. Many plugins use many resources for a simple function that could be hard-coded into the theme. “Adding new hardware and server resources isn’t always the solution,” said Ewdison Then, “but sometimes it’s the only solution.”

Optimize What Matters

Mark Jaquith recommends that you don’t optimize blindly. “Find out what the biggest bottlenecks are and eliminate them. Rinse and repeat.”

WordPress Performance Resources

If you feel inspired to start scaling, here are some resources to check out:

Many thanks to all of the people who contributed their knowledge to this post:

(al)


© Siobhan McKeown for Smashing Magazine, 2012.

Google releases Course Builder, takes online learning down an open-source road

By Jon Fingas, EngadgetSeptember 11, 2012 at 08:32PM

Google releases Course Builder, takes online learning down an opensource road

Google is well-known for projects with unexpected origins. It’s almost natural, then, that the code Google used to build a web course has led to a full-fledged tool for online education. The open-source Course Builder project lets anyone make their own learning resources, complete with scheduled activities and lessons, if they’ve got some skill with HTML and JavaScript. There’s also an avenue for live teaching or office hours: the obligatory Google+ tie-in lets educators announce Hangouts on Air sessions. Code is available immediately, although you won’t need to be grading virtual papers to see the benefit. A handful of schools that include Stanford, UC San Diego and Indiana University are at least exploring the use of Course Builder in their own initiatives, which could lead to more elegant internet learning — if also fewer excuses for slacking.

Filed under:

Google releases Course Builder, takes online learning down an open-source road originally appeared on Engadget on Tue, 11 Sep 2012 20:32:00 EDT. Please see our terms for use of feeds.

Permalink Google Research Blog, TechCrunch  |  sourceCourse Builder  | Email this | Comments

How to find MySQL queries worth optimizing ?

By Peter Zaitsev, MySQL Performance BlogSeptember 11, 2012 at 05:45PM

One question I often get is how one can find out queries which should be optimized. By looking at pt-query-digest report it is easy to find slow queries or queries which cause the large portion of the load on the system but how do we know whenever there is any possibility to make this query run better ? The full answer to this question will indeed require complex analyses as there are many possible ways query can be optimized. There is however one extremely helpful metric which you can use – ratio between rows sent and rows analyzed. Lets look at this example:

# Time: 120911 17:09:44
# User@Host: root[root] @ localhost []
# Thread_id: 64914  Schema: sbtest  Last_errno: 0  Killed: 0
# Query_time: 9.031233  Lock_time: 0.000086  Rows_sent: 0  Rows_examined: 10000000  Rows_affected: 0  Rows_read: 0
# Bytes_sent: 213  Tmp_tables: 0  Tmp_disk_tables: 0  Tmp_table_sizes: 0
# InnoDB_trx_id: 12F03
use sbtest;
SET timestamp=1347397784;
select * from sbtest where pad='abc';

The query in this case has sent zero rows (as there are no matches) but it had to examine 10Mil rows to produce result. What would be good scenario ? – query examining same amount of rows as they end up sending. In this case if I index the table I get the following record in the slow query log:

# Time: 120911 17:18:05
# User@Host: root[root] @ localhost []
# Thread_id: 65005  Schema: sbtest  Last_errno: 0  Killed: 0
# Query_time: 0.000323  Lock_time: 0.000095  Rows_sent: 0  Rows_examined: 0  Rows_affected: 0  Rows_read: 0
# Bytes_sent: 213  Tmp_tables: 0  Tmp_disk_tables: 0  Tmp_table_sizes: 0
# InnoDB_trx_id: 12F14
SET timestamp=1347398285;
select * from sbtest where pad='abc';

Rows_examined=0 same as Rows_sent meaning this query is optimized quite well. Note you may be thinking in this case there is no database access happening at all – you would be wrong. The index lookup is being perform but as only actual rows which are found and returned up to the top level MySQL part for processing are counted the Rows_examined remains zero.

It looks simple so far but it also a huge oversimplification. You can do such simple math only to the queries without aggregate functions/group by and only to ones which examine one table only. What is about queries which query more than one table ?

# Time: 120911 17:25:22
# User@Host: root[root] @ localhost []
# Thread_id: 65098  Schema: sbtest  Last_errno: 0  Killed: 0
# Query_time: 0.000234  Lock_time: 0.000063  Rows_sent: 1  Rows_examined: 1  Rows_affected: 0  Rows_read: 1
# Bytes_sent: 719  Tmp_tables: 0  Tmp_disk_tables: 0  Tmp_table_sizes: 0
# InnoDB_trx_id: 12F1D
SET timestamp=1347398722;
select * from sbtest a,sbtest b where a.id=5 and b.id=a.k;

mysql> explain select * from sbtest a,sbtest b where a.id=5 and b.id=a.k;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | a     | const | PRIMARY,k     | PRIMARY | 4       | const |    1 |       |
|  1 | SIMPLE      | b     | const | PRIMARY       | PRIMARY | 4       | const |    1 |       |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------+
2 rows in set (0.00 sec)

In this case we actually join 2 tables but because the access type to the tables is “const” MySQL does not count it as access to two tables. In case of “real” access to the data it will:

# Time: 120911 17:28:12
# User@Host: root[root] @ localhost []
# Thread_id: 65099  Schema: sbtest  Last_errno: 0  Killed: 0
# Query_time: 0.000273  Lock_time: 0.000052  Rows_sent: 1  Rows_examined: 2  Rows_affected: 0  Rows_read: 1
# Bytes_sent: 719  Tmp_tables: 0  Tmp_disk_tables: 0  Tmp_table_sizes: 0
# InnoDB_trx_id: 12F23
SET timestamp=1347398892;
select * from sbtest a,sbtest b where a.k=2 and b.id=a.id;

+----+-------------+-------+--------+---------------+---------+---------+-------------+------+-------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref         | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+-------------+------+-------+
|  1 | SIMPLE      | a     | ref    | PRIMARY,k     | k       | 4       | const       |    1 |       |
|  1 | SIMPLE      | b     | eq_ref | PRIMARY       | PRIMARY | 4       | sbtest.a.id |    1 |       |
+----+-------------+-------+--------+---------------+---------+---------+-------------+------+-------+
2 rows in set (0.00 sec)

In this case we have 2 rows analyzed for each row set which is expected as we have 2 (logical) tables used in the query.

This rule also does not work if you have any group by in the query:

# Time: 120911 17:31:48
# User@Host: root[root] @ localhost []
# Thread_id: 65144  Schema: sbtest  Last_errno: 0  Killed: 0
# Query_time: 5.391612  Lock_time: 0.000121  Rows_sent: 2  Rows_examined: 10000000  Rows_affected: 0  Rows_read: 2
# Bytes_sent: 75  Tmp_tables: 0  Tmp_disk_tables: 0  Tmp_table_sizes: 0
# InnoDB_trx_id: 12F24
SET timestamp=1347399108;
select count(*) from sbtest group by k;

This only sends 2 rows while scanning 10 million, while we can’t really optimize this query in a simple way because scanning all that rows are actually needed to produce group by results.
What you can think about in this case is removing group by and aggregate functions. Then query would become “select * from sbtest” which would send all 10M rows and hence there is no ways to simply optimize it.

This method does not only provide you with “yes or no” answer but rather helps to understand how much optimization is possible. For example I might have query which uses some index scans 1000 rows and sends 10… I still might have opportunity to reduce amount of rows it scans 100x, for example by adding combined index.

So what is the easy way to see if query is worth optimizing ?
– see how many rows query sends after group by, distinct and aggregate functions are removed (A)
– look at number of rows examined divided by number of tables in join (B)
– if B is less or equals to A your query is “perfect”
– if B/A is 10x or more this query is a very serious candidate for optimization.

This is simple method and it can be used with pt-query-digest very well as it reports not only average numbers but also the outliers.

The New Feedly Makes Your News Feeds Look Good, More Fun to Read and Share with Friends [Video]

By Alan Henry, LifehackerSeptember 10, 2012 at 04:30PM

iOS/Android: Feedly, one of your favorite news aggregators, has completely overhauled its mobile apps with a brand new interface, new ways to discover interesting stories and news events that interest you, and faster sharing options so you can tell your friends what you just read.

Feedly has always been a fast, sharp-looking way to browse the latest articles from your favorite blogs and news sites, but today’s update adds a new “categories” pane where you can switch from topic to topic quickly, supports Pocket and Instapaper so you can save long articles for later, has multiple themes and customizable fonts, and even shows you how popular a given article is on Facebook or Twitter so you can see if everyone’s already talking about it. Plus, the new UI is simply gorgeous, offering a very Flipboard-like layout that’s fast and fun to use.

As always, your Feedly articles and data are saved and synced across all of your devices, and you have total control over which feeds you read and which topics bubble to the top of your reading list. Feedly is available on mobile devices and as a browser add-on for Firefox, Chrome, and Safari. The new mobile apps are available now in the iTunes App Store and at Google Play.

Feedly (Free) | Google Play

Feedly (Free) | iTunes App Store

Factura Organizes Your Never-ending File Archive [Mac Downloads]

By Adam Dachis, LifehackerSeptember 10, 2012 at 04:00PM

Factura Organizes Your Never-ending File ArchiveDesktop and folder clutter happens when we download and create files but don’t bother to clean up and organize them afterwards. While there are ways to automate this process, it doesn’t provide full control over where your stuff goes. Factura is a drag-and-drop app that makes file archiving on your Mac easy.

To use Facture, you just drop any files you want to archive, give it a category name, and hit return. It’ll automatically create a folder in the archive directory of your choice and move (or copy) the file you want to archive. It’ll also prepend the date to the file name so everything is sorted in the order it was archived. This will make your archives easier to browse as files will be sorted just how you specified. It still takes a little effort on your part, but cleaning up well should.

Factura (Free) | iTunes App Store via Addictive Tips

10 Questions You Should be Asking Every Photographer

By Darren Rowse, Digital Photography SchoolSeptember 10, 2012 at 03:20PM

RightQuestions.jpgOver the last two years, I had the privilege of interacting with many talented photographers from around the world discussing their work, vision and style of photography.

My first ‘victim’ was Jyothy Karat – a photo documenter. I wanted a set of compelling and illuminating questions that could help a newbie start. But I had no clue as to what I should be asking. No amount of googling did help either.

But little did I realize at that time that I had the opportune blessing of being both ignorant and curious about photography. I sat down thinking about the questions that I wanted to be answered and clarified. After an hour or so, I did come up with some interesting questions.

Given below are a handful of questions that I use as a starter on every photographer that I interview.

Q1. What kind of gear do you use?

  • Camera body –
  • Lens –
  • Tripod –
  • Filters –
  • Flash –
  • Camera bag –
  • Mention others, if any.

Q2. Which is your favorite lens? Why?

Q3. When you go in one of your travels, what all you take with you? Why?

Q4. Among the gadgets that you own, is there something that you wish you hadn’t bought? Why?

Q5. In the field, what are your settings?

  • Aperture –
  • Shutter Speed –
  • ISO –
  • White Balance –
  • Focus – Manual/Auto
  • Image Format – RAW/JPEG

Q6. What kind of tools do you use for post processing? Explain your work flow.

Q7. How do you educate yourself to take better pictures?

Q8. Among your works, which one is your favorite? Why?

Q9. Whose work has influenced you most?

Q10. What is the one thing you wish you knew when you started taking photos?

These questions have revealed interesting aspects and insights in to each one of the interviewees. Hope these help you to get started.

NoteComplete list of Interviews is available here.

anees k A is a photography enthusiast who likes to explore the wild. He call his clicks -’clickography‘ – all of them ‘clucked’ using his d90. He tweets as @aneeskA.

Post originally from: Digital Photography Tips.

Check out our more Photography Tips at Photography Tips for Beginners, Portrait Photography Tips and Wedding Photography Tips.

10 Questions You Should be Asking Every Photographer

A Guide To iOS SDK For Web Designers // App development

By James Brocklehurst, Smashing Magazine FeedSeptember 10, 2012 at 09:06AM


  

As a designer looking to broaden your skill set, you’ve decided that learning to make native apps for Apple’s iOS platform is an attractive and potentially lucrative prospect. With a frisson of excitement, you start to do some research. The euphoria is short-lived however, as you quickly discover that unless you are an experienced programmer, the task is far from easy.

The documentation provided by Apple is aimed at those with a degree in computer science. Books on iOS development ask that you have a good grasp of Objective-C from the opening page. Online tutorials vary in quality, with many appearing out of date or contradictory.

This post will help you get to know the iOS SDK a little better. It leads you through some choreographed steps of iOS app development, even if you have little or no programming knowledge. It covers some key principles and applies these directly to something useful and relevant: the creation of a simple but functioning portfolio app for the iPhone.

The result will look like this:

iOS Portfolio App

Going Native?

By “native” iOS development, we mean using Apple’s software development kit (SDK) and the programming language Objective-C to author apps for the iPhone, iPod Touch and iPad. Before we learn how to do this, it is worth mentioning why we would want to make an app this way, and what the alternatives might be.

In relaxing the App Store’s submission review guidelines in September 2010, Apple made it easier for developers to use third-party frameworks and more familiar languages, such as HTML, CSS and JavaScript, to create apps. Examples of such tools are Appcelerator’s Titanium Mobile, Nitobi’s PhoneGap (acquired by Adobe in 2011) and appMobi’s XDK, among others. In addition to the benefit of using the more familiar Web languages of HTML, CSS and JavaScript to author apps, these methods enable developers to output to other mobile platforms, such as Android and BlackBerry, with minimal rewriting of the source code.

The disadvantage of using third-party tools is that the resulting app will not be quite as efficient as one that is natively authored, and the newest features of the operating system and hardware will not be available, at least until the framework catches up. Each framework also has its own fairly extensive library of functions that have to be learned, along with its own idiosyncrasies, bugs and workarounds. Plus, to publish your app to the App Store, you need to use Apple’s Xcode, the application used to work with the iOS SDK, so limited familiarity with native processes is still necessary.

A few “third way” solutions, such as Cocos 2D for iPhone and PugPig, are also available, allowing you to connect framework files to an Objective-C project for a particular aim, such as to create a game or magazine app. To make use of these and any others that come along in future, you will need a basic understanding of the SDK.

Therefore, if you are interested in developing for the iPhone, iPod and iPad and you accept that whatever authoring method you choose means having to find your way around Xcode, then getting to grips with the native SDK is a recommended first step.

Getting Started

You will need two things to be able to start working with the iOS SDK:

  • A Mac, running the latest version of OS X (there is currently no way to author natively for iOS on Windows or Linux, although apparently there is a workaround);
  • Apple’s Xcode application.

To get Xcode, download it from the Mac App Store. It’s free but weighs in at nearly 1.5 GB and can take about half an hour to install, so you’ll need to put aside a bit of time to get it up and running.

Preparing Graphics

While waiting for that download to complete, we can look at how you might prepare and export graphics for iOS using Photoshop.

Because all iOS applications have one of two possible pixel densities (standard or Retina), you should aim to work in Photoshop using non-destructive techniques to reduce the need to design twice. This means creating buttons and interface elements using vector shapes and layer styles, and using smart objects for images, where possible. The recommended approach is to work at a Retina-display resolution first, and then scale down to standard resolution once the design is complete. Sometimes you will find that scaling down produces poor results, and you will have to tweak your smaller designs.

Plenty of templates with pre-built iOS system elements are available on the Web. Teehan + Lax has one that is pretty good and widely used. Apart from saving you from having to draw iOS system components from scratch, they also demonstrate how much space is left for content, once elements such as the status, navigation and tool bars are in place.

To set up a new blank iPhone document in an image editor, these are the settings you will need:

  • 640 × 960 pixels,
  • 72 DPI,
  • RGB color mode.

The above is for a Retina display (iPhone 4+ and iPod Touch fourth generation and up). Older devices are 320 × 480 pixels, exactly half the size!

See Marc Edwards’ “Designing for iPhone 4 Retina Display” for more information on iOS design techniques and workflows.

Some Quick Image Exporting Tips

  • iOS accepts a number of image formats, but PNG is recommended because of its support for alpha-transparency and its lossless compression.
  • Graphics for buttons should, in most cases, be exported just as background images, without accompanying text, because this allows for localization (in different languages), accessibility and text resizing between the Retina- and standard-display resolutions.
  • If exporting a button graphic, ensure that the pixels of the actual button are centered in the frame of the exported image, because Interface Builder doesn’t give you precise control over the positioning of button background images or foreground text. You might need to manually compensate for a drop shadow on the opposite sides, for instance.
  • Where possible, flatten design elements made from multiple layers into a single image file. Rebuilding layered UI components in Interface Builder can be a pain; plus, reducing the number of resources that your app uses will make it run quicker and take up less memory. Only interface components that need to respond to user interaction should be animated, and only interface components that will be controlled by the application should be exported as separate image files.
  • You will need to produce Retina and standard versions of every exported image and give them identical names, with a @2x suffix for the Retina version, like so:
    • image.png
    • image@2x.png
  • You can use my SuperSlicr Photoshop action (included in the package) to automate the scaling and exporting of elements from your PSD file.
  • Every pair of images that you make will need a unique and descriptive file name, because they are all stored in the same directory in the app bundle. File names should have only alphanumeric characters (no symbols), and underscores or hyphens instead of spaces. You may use capitalization.
  • Photoshop isn’t very good at compressing PNGs, so run them through porneL’s ImageOptim to reduce their size before importing into Xcode. Xcode will also try to apply its own compression to imported images, which can sometimes increase file size, but this can be disabled.

Xcode Overview

You’ve successfully installed Xcode? Great!

Next, you will need to download and unzip these template files. The package includes a source PSD, some exported PNGs and the required starter code.

In the package, navigate to the folder named Begin Here. Locate the Xcode project document named Portfolio.xcodeproj. Double-click on this file to open it in Xcode.

Once the document has loaded, click on the blue project icon on the left named Portfolio, 1 target, iOS SDK, and you should see a project summary screen in the main Xcode interface, as shown below. We will look at the contents of the summary screen in detail later.

Xcode Overview

The “Navigator” area on the left lists all of the files already associated with your project. These can be expanded out from the blue project icon. We will be mostly interested in those contained in the yellow Portfolio folder, or “group.” Three types of files are here:

  • .h
    A “header” (or interface) file.
  • .m
    A “message” (or implementation) file.
  • .xib
    An “XML interface builder” file, sometimes referred to as a NIB.

The “Editor” area will change depending on what task you are performing. Because we currently have the blue project file selected in the navigator, we are given the “Target Summary” screen. This gives us some basic options for our app, including which device types, iOS version and display orientation we want our app to support. We can also specify images to use for our app’s icon and launch image, which we will look at in detail later.

Single-click on TestAppDelegate.m. The editor area will now turn into a code editor and display the code contained in this file.

Now single-click on MainWindow.xib in the navigator area. The editor area will display Interface Builder, an integrated graphical user interface (GUI) for putting together the front-end of your application.

Interface Builder Overview

The “Inspector” has some tabbed controls at the top that you will need to be familiar with. The last four are the most important:

Inspector Bar

The other important control is the big “Run” button in the top-left corner of Xcode. Pressing this will compile your project code into an app and then run it in an iOS simulator so that you can see whether it works without having to load it onto an actual device. If you press it now, it should launch the simulator and present you with a big virtual iPhone on your desktop.

The iOS Simulator

The simulator works similar to an actual device. Have a play to see how it behaves. Under the “Hardware” menu, you can select different devices and iOS versions and simulate rotating and shaking the device. Holding alt allows you to pinch and zoom. The home button works, taking you to the springboard where there is even a functioning version of mobile Safari (which, incidentally, is great for testing locally hosted websites).

A more detailed guide to the interface is available in Apple’s “Xcode 4 User Guide.”

Importing Graphics Into Xcode

The template package that you downloaded earlier contains some sample image files. You can either use these or use your own for the next section.

To import images into your project, Control-click on the “Images” group in the project navigator and select “Add Files to ‘Portfolio.’”

Adding Images

Browse to the “PNGs” folder in the downloaded package and select all of the images. Check the “Copy items into destination group’s folder” box, and then click “Add.”

The images have now been imported into your project and are available to Xcode and Interface Builder. You can add more graphics to the “Images” group at any time by following this same process.

Editing The Template Without Writing Any Code

There is a debate in the iOS development community about whether one should build an app purely in code or with XIB files generated by Interface Builder and its GUI. Both methods seem to be supported by Apple, and each project necessitates its own approach. Developers who frown on the use of Interface Builder perhaps overlook the power of this tool, which enables us to establish the structure and outward appearance of our app efficiently and visually. For designers used to working with Adobe’s Creative Suite, this will be (almost) familiar territory. For this reason and because our app will be very “view-based,” we will use Interface Builder to begin with.

First, we will look at setting up some different screens, or “views,” that can be switched using some Tab Bar controls. Click on MainWindow.xib in the project navigator to bring up Interface Builder. In the library, select the “Show the Object Library” tab icon (the one that looks like a cube), and scroll through the list of objects until you find “View Controller.”

View Controller Object

Expand the dock using the circular “Expand document outline” button at the bottom, then drag an instance of the View Controller object from the library onto the “Tab Bar Controller” in the dock. The Tab Bar Controller should expand, showing the View Controller nested inside.

Repeat this process twice more, until you have three View Controllers nested inside the Tab Bar Controller. The canvas area should also show the Tab Bar as having three unnamed tabs.

View Controllers Added To Tab Bar

View Controllers?

If you are wondering what a “View” and a “Controller” are, they are part of something called the “Model View Controller” (MVC) paradigm. This is an approach to programming that separates application data, logic and presentation to make things easier to work with. “Model” refers to the back-end aspect that manages data. “View” refers to the front-end user interface. “Controllers” bridge the front and back ends and enable things to happen in your app. We won’t be working with any stored data in this article, so we will only be encountering Views and their corresponding Controllers.

Creating Classes

We need to create some “classes” to generate each of our views; and because we are new to programming, this requires a bit of explanation first.

In object-oriented programming languages such as Objective-C, classes are used as a way to define elements within the application called “objects.” A class defines the qualities (or properties) that an object may have and what it can do (methods). It can then be asked to generate one or more “instances” of an object based on this definition, and these instances are used to make your application work.

Each of the three views that we want to make are objects, so we need to create some classes to be able to conjure them into existence.

To add a new View Controller class, Control-click on the yellow “Portfolio” folder in the navigator, and select “New File” from the contextual menu. In the sidebar of the options sheet that follows, select “Cocoa Touch,” then “Objective-C class.”

New Objective-C Class

Click “Next.” Then, in the sheet that follows, enter “HomeViewController” in the “Class” field, select “UIViewController” in the “Subclass of” drop-down menu, and ensure that the “With XIB for user interface” box is checked.

Naming New View Controller

Clicking “Next” will give you a save dialogue box. Select the “Begin Here > Portfolio” folder, and then hit “Create.”

Repeat this process for the other two views, naming each class “PortfolioViewController” and “ContactViewController,” respectively.

You can rearrange the order of the files in the navigator by dragging and dropping if you want. It should now look something like this:

View Controllers Added To Project Navigator

Configuring Tabs and Views

Return to MainWindow.xib. Select the first View Controller icon in the dock, then the Identity inspector. Select “HomeViewController” from the “Class” drop-down menu.

Connecting HomeViewController Class

Now go to the Attributes inspector. Type “Home” in the “Title” field, and select “HomeViewController” as the NIB name.

Connecting HomeViewController XIB

Expand the View Controller in the dock and select its “Tab Bar Item.” In the Attributes inspector, set the title as “Home,” and select tab-icon-home.png from the Image drop-down menu. You don’t need to specify the @2x Retina version when selecting images in Xcode because they are called automatically when the application is running.

Customizing Tab Name And Icon

Repeat the above process for the Portfolio and Contact views, choosing the relevant classes, titles and image files.

The color of the tab bar highlight can be changed by selecting the main “Tab Bar” object in the dock, then “Image Tint” in the Attributes inspector. Although custom tints will only show up in devices running iOS 5 or higher, iOS 4 and below will safely fall back to showing the default blue highlight color.

Our views within tabs are now all set up! To check that they are working properly, we’ll need to add some dummy content to each view.

Select HomeViewController.xib in the navigator, then drag a “Label” from the library (at the top of the list) onto the view represented in the canvas. Double-clicking on the label in the canvas will allow you to edit its text. Change it to “Home.”

Adding A Label To The Home View

Repeat this for PortfolioViewController.xib and ContactViewController.xib, naming the labels appropriately.

Now hit the “Run” button, and check out your already functioning tabbed app in the simulator!

App Test With Labels

Adding Graphics And Text To The Views

As with desktop publishing applications, inserting images and text in Interface Builder requires you to make a containing element first. These can be dragged onto the canvas from the library, and they are called “Image View” and “Text View,” respectively. They can be repositioned and resized visually with the cursor, or you can type pixel measurements into the Size inspector for more precise control.

The Attributes inspector allows us to specify an image to place in the Image view. We may only choose from images that have been imported into the project.

The Attributes inspector also lets us set text for the Text view, and it gives us typography controls, a background color-picker and scrollbar options.

Arrange the graphics for HomeViewController.xib. Delete the label, and drag on an Image view from the library, setting its image’s name to home-bg.png and its mode to “Top Left” using the Attributes inspector.

Attributes Inspector Select Image

In the Size inspector, check that the Image view has an X value of 0, a Y value of -20, a width of 320 and a height of 480.

The Size Inspector

Next, position a Text view over top. Editing its content, center-align the text, set the text’s color to white, set a custom font (Snell Roundhand, Regular, 24 pixels), and set the background color to “Clear.”

Attributes Inspector Text View Controls

The result should look like this:

Adding Graphics To Home

Because our views are being placed inside a tab bar interface, we also need to simulate the black strip at the bottom of each view so that we can arrange items with this in mind. To do this, select the main “View” object in the dock. Then, in the Attribute inspector, under “Simulated Metrics,” choose “Tab Bar” from the “Bottom Bar” drop-down menu:

Simulated Metrics

This won’t actually add a tab bar to our view. It simply provides a visual reference to help us position the layout.

Now, have a go at arranging the graphics and text for the Portfolio and Contact views. Either use the sample images at the top of this article, or refer to the source PSD provided in the template package.

When creating the thumbnail images in the Portfolio view and the social media buttons in the Contact view, use the “Round Rect Buttons” from the library instead of Image views. If you set the button type to “Custom” in the Attributes inspector, you can then set the button’s image in the same way as you would for an Image view. Set the button size in the Size inspector based on the image’s original dimensions. Using a “Round Rect Button” instead of an Image view allows us to add interactivity to them later.

Now, build and run to check that everything works OK in the simulator.

Extra Finesse

If you press the simulator’s home button, you will notice that your app has an uninspiring white icon on the springboard and a blank screen when it relaunches. Let’s fix that now.

Clicking on the blue “Portfolio” project icon in the navigator will take you back to the summary screen. Scrolling to the bottom of this screen will reveal empty wells awaiting custom images. Adding images is simply a case of dragging them from the Finder to the relevant well.

App Icon And Launch Image Wells

You will find the images you need for this project in the “App Icons” directory in the downloaded package.

If you want to make your own app icon, the images need to conform to the following sizes:

  • Standard: 57 × 57 pixels,
  • Retina: 114 × 114 pixels.

The launch images need to be the same as the display’s overall dimensions:

  • Standard: 480 × 320 pixels,
  • Retina: 960 × 640 pixels.

You will at a later date need some more sizes to display your app correctly in various contexts. An excellent resource detailing the required sizes has been produced by Neven Mrgan. Apple’s “iOS Human Interface Guidelines” also give a good breakdown and include icon and launch image sizes for the new iPad.

iOS automatically rounds the corners of your app’s icon and overlays the standard glossy sheen on it, too, so you don’t need to include these elements in your design.

If, however, you want to create your own non-standard glossy effect or you don’t want gloss on your icon at all, then check the “Prerendered” box to the right of the App Icon wells.

Icon Prerendered Example

To change the name that appears below the icon, select the “Info” tab next to the “Summary” tab at the top of the editor. This will reveal an editor for the app’s .plist (property list) file, which is an XML document containing the main settings for your app:

App Info Plist

Some of the information here, such as “Main nib file base name,” points to resources required by the app when it first launches. Other information, such as “Bundle Identifier,” is used in the black art of provisioning and uploading to iTunes Connect for distribution on the App Store.

To change the name below the icon, change the “Bundle display name” value from ${PRODUCT_NAME} to whatever you want.

The Minor Miracles Of The Xcode Assistant Editor

When we test our app, the custom buttons will respond to being tapped but won’t actually do anything. To make them work, we’ll need to write some code. Luckily, something called the Assistant Editor can help us with the first part of this process.

Select ContactViewController.xib from the navigator. Then, press the “Assistant Editor“ button in the top right of the Xcode window.

Assistant Editor Toggle

This will display an Interface Builder window detailing ContactViewController.xib, alongside a Code Editor window, which shows the associated ContactViewController.h interface document. In the example below, the dock has been minimized, and the Utility area hidden to give the two editors more room. The Code Editor is also using the “Dusk” theme, which can be found under “Fonts and Colors” in Xcode → Preferences.

The Assistant Editor In Action

Miracle 1: Declaring Properties and Methods

Features of a class generally fall into two main types: a “property,” which is a characteristic that the class might possess, and a “method,” which is something that it can do. When adding a button to ContactViewController, we need to declare the button as a property of the class and create a method for what happens when the button is tapped by the user.

The .h document should contain the following code:

#import <UIKit/UIKit.h>
@interface ContactViewController : UIViewController
@end

The #import statement at the top gives the class access to the required iOS user interface classes stored within the UIKit framework.

The @interface declaration starts by defining ContactViewController and stating that it is a subclass (meaning that it inherits all the features) of the UIViewController class, which is defined within UIKit.

We can add in extra items between the opening @interface declaration and its @end, to build on the foundation provided by the UIViewController class.

To do this, Control-click on our orange “WWW” button on the canvas in Interface Builder, drag the cursor to be just above @end in the code editor, and then release. A little dialogue box will pop up with some settings:

Outlet Dialogue

Check that the “Connection” is set to “Outlet,” type in the name websiteButton, and then press “Connect.” Xcode will insert a line of code into the .h document for you.

Repeat the process, this time changing “Connection” to “Action” and providing the name openWebsite.

Action Dialogue

The code in your .h document should now look like this:

#import <UIKit/UIKit.h>
@interface ContactViewController : UIViewController
@property (retain, nonatomic) IBOutlet UIButton *websiteButton;
- (IBAction) openWebsite:(id)sender;
@end

So, what does this all mean?

The @property declaration states that the ContactViewController class has a property. It begins with some parameters: retain, which has to do with memory management (more on this later), and nonatomic, which means that it is not “multithreaded,” something that is common to all iOS properties. Next, there is a definition for the property return type, IBOutlet, which allows us to bind our code to the button we created in Interface Builder. UIButton states that the property will inherit from the UIButton class, defined within UIKit, and then the name of our property is given, which is websiteButton.

The second line of code is a method declaration. It starts by saying that it is an IBAction, which again lets us bind the code to the button object in the XIB. Then it is given a name, in this case, openWebsite. The (id)sender parameter tells us which object called the method. This is handy in certain situations, although we don’t need it right now.

You might have noticed that when we created our View Controller classes, their names began with an uppercase letter, whereas the names we gave our property and method didn’t. This is an Objective-C naming convention and should be adhered to.

Hand-coding those two lines is possible, but using the Assistant Editor to do it saves a bit of time and ensures that the syntax is correct. It also performs a whole series of other tasks for us as well. Let’s look at what else it does.

Miracle 2: Property Synthesis and Memory Management

Return to “Standard Editor” mode, and select ContactViewController.m. Around line 12, you should see this directive that the assistant has put in for us:

@synthesize websiteButton;

This will ask the compiler to “synthesize” some extra methods for us when the app is built, for setting and getting variables for our property. This all happens behind the scenes and saves us from having to deal with even more code, so it really is useful.

Lower down, we find the following:

- (IBAction)openWebsite:(id)sender {
}

This is the method implementation for our button action. In a minute, we will put some code in there to make our button work.

You should also find another method implementation that looks like this:

- (void) dealloc {
[websiteButton release];
[super dealloc];
}

This method has to do with memory management and is defined within the Cocoa framework, which is why we haven’t needed to mention it in our interface.

Managing memory is very important when programming because a mobile device doesn’t have much to play with. When the websiteButton property is defined, a chunk of memory is allocated to it using the retain command. This command asks iOS to reserve a bit of memory for the button until we tell it to let it go. The dealloc method is activated only when the View instance is destroyed; so, by putting websiteButton release in there, we are asking iOS to free up the memory set aside for the button when this event occurs. If we don’t do this, then the memory keeps getting allocated, even when the button object isn’t in use anymore. This is called a “memory leak.” If left unchecked, these leaks will add up, affecting the app’s responsiveness and the device’s battery life and causing all sorts of other horrors!

Thankfully, once again, the assistant editor has set this all up for us, so we don’t need to remember to do it. Hooray!

It is probably worth mentioning that version 5 of the iOS SDK comes with “Automatic Reference Counting” (ARC), which seeks to further automate memory management for iOS developers. When creating a new project, you have the option to turn ARC on and off. We are not using ARC in this project, so we can learn a bit about how memory management works. Integrating freely available components found on the Internet (many of which are written using manual reference counting) with an ARC-enabled project can also be difficult. With each subsequent release of the SDK, however, Apple is pushing more and more for developers to embrace ARC, and there are many advantages in doing so. ManiacDev has compiled some useful resources to make this transition smoother.

Miracle 3: Code Binding

The Assistant Editor has also connected our code to the button object in the XIB. Select ContactViewController.xib, expand the dock, and under “Placeholders” select “File’s Owner.” This represents the ContactViewController class. Now, select the Connections inspector. It should look like this:

Connections Inspector

Under “Outlets,” we can see the websiteButton property linked to the Button XIB object.

Under “Received Actions,” we can see that the openWebsite method is also connected to the Button.

Under it, there is also an associated event, “Touch Up Inside.” This means that the method will be called when the user touches and then releases their finger while still inside the button. This is the default touch event.

Handwriting Your First Bit Of Objective-C

Lets make that button do something!

Change the openWebsite method implementation in ContactViewController.m so that it looks like the following:

- (IBAction)openWebsite:(id)sender {
NSURL *webAddress = [NSURL URLWithString:@"http:www.mightymeta.co.uk"];
[[UIApplication sharedApplication] openURL:webAddress];
}

The syntax for a method is fairly straightforward. Simply provide the name of the method, and then put what you want to happen when the method is called between the pair of curly braces.

In this case, we are doing two things. First, we are creating a temporary variable named webAddress and assigning it a string of text that contains our email URL.

It is worth noting that this is something called a “convenience method.” It creates an instance of the NSURL class and automatically allocates some memory to it. It also sorts out the memory deallocation for you, so you don’t have to worry about releasing the webAddress variable.

The second line asks the OS to open the URL in a relevant application, which in this case would be the default Web browser.

Build and run to test whether it works.

To make the other buttons work, simply repeat the steps that we went through to create this button. Any mailto: URLs will work and will launch the default mail client. To make a phone call, put tel:, followed by the number you want to dial in place of the URL. You can change the name of the temporary variable to suit the purpose for each button.

Making a View Appear Modally

The portfolio section currently has some thumbnail images. Wouldn’t it be great if the user could tap on these to get bigger versions?

This can be achieved by creating what is called a “Modal View.” This is essentially a new view that is placed over top the previous one, and it comes with a range of animated transitions into view.

Create the Modal View

Modals are easy to create. First, generate a new class called BigImageViewController (Control-click on the “Test” folder in the project navigator, select “New File” and then the UIViewController subclass).

Open the corresponding XIB in Interface Builder, add an Image view that fills the entire view, and set its image as portfolio-modal-bg.png. Add a custom Round Rect button, give it a background of button-close.png, set the color of the “Close” title to white, and place it in the top-left corner.

Next, place another image view over top the first. Fit it to near the edges of the paper background, but don’t assign an image to it:

Creating A Modal View

Use the Assistant Editor to declare the empty Image view as an outlet named imageFrame, and connect the button to an action named closeView in BigImageViewController.h (you can select which file the right-hand window will display from the bar at its top):

@property (retain, nonatomic) IBOutlet UIImageView *imageFrame;
- (IBAction)closeView:(id)sender;

Then type the following into the closeView method in BigImageViewController.m:

- (IBAction)closeView:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}

This code will close the modal view when the button is tapped.

Code for Launching the Modal

Now, using the Standard Editor, type in PortfolioViewController.h so that it looks like the following example:

#import <UIKit/UIKit.h>
#import "BigImageViewController.h"
@interface PortfolioViewController : UIViewController
@property (nonatomic, retain) UIImage *bigImage;
- (IBAction) selectImage1;
- (void) openBigImageView;
@end

Make sure to include the #import statement for the BigImageViewController header file. This is required so that we can send a message to this class and ask it to create an instance of itself.

A property and two method declarations are there. The second, openBigImage, doesn’t need to be connected to any objects in the XIB; so, it has a return type of (void), meaning… well, a big black hole of nothingness.

We haven’t used the Assistant Editor here because we are doing something a little different from before. Because of this, we need to manually synthesize and release the bigImage property at the start of PortfolioView.m, like so:

@implementation PortfolioViewController
@synthesize bigImage;
- (void) dealloc {
[bigImage release];
[super dealloc];
}

Underneath the dealloc method, implement the two methods that we declared in the header:

- (IBAction) selectImage1 {
self.bigImage = [UIImage imageNamed: @"image1-big.png"];
[self openBigImageView];
}
- (void) openBigImageView {
BigImageViewController *bigImageView = [[[BigImageViewController alloc] initWithNibName:@BigImageViewController bundle:nil] autorelease];
bigImageView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:bigImageView animated:YES];
[bigImageView.imageFrame setImage:bigImage];
}

Wow, that’s a lot to take in. Lets go through it.

The selectImage1 method sets the bigImage property to the image file that we want to use, and then calls the openBigImageView method.

The openBigImageView creates an instance of the BigImageViewController class named bigImageView, presents it as a modal using the “flip” transition style, and then sends its imageFrame the image file held by the bigImage property.

Because we have manually allocated memory to the instance of BigImageViewController, we need to release it at some point, but we don’t know how long the object will be needed for because it depends on how long the user keeps the modal active. The autorelease command helps us with this problem because it asks iOS to hold on to the memory for a bit and then release it later on, when it is deemed safe to do so.

Manual Code Binding

Now we need to connect our code to the objects in the XIB. Select PortfolioViewController.xib, and then the “File’s Owner” object in the dock, and then the Connections inspector.

Under “Received Actions,” you will find the selectImage1 method, and an empty circle to the right of it. Click and drag a connection from this circle over to the relevant thumbnail button:

Binding A Button To Code Manually

Select “Touch Up Inside” from the list of button events that appears.

Build and run to see whether it works. If everything is in place, you should be able to tap the thumbnail to reveal the bigger image.

See if you can work out how to do the same for the other images on the portfolio page. You will need to create selectImage2, selectImage3 and selectImage4 methods, but you won’t need another openBigImage. You could also try using different transition styles; you have four to choose from:

  • UIModalTransitionStyleCoverVertical
  • UIModalTransitionStyleCrossDissolve
  • UIModalTransitionStyleFlipHorizontal
  • UIModalTransitionStylePartialCurl

If you get really stuck, have a look at the completed project in the “End Result” folder of your downloaded template package.

In Conclusion

We’ve covered quite a lot of ground, having looked at the basics of the Xcode interface and how to arrange visual elements in Interface Builder. We’ve also been introduced to the key concepts of classes, properties, methods and memory management in Objective-C.

In the process, we have built a functioning, albeit limited, app. Making it ready for submission to the App Store would require a unique design and some additional functionality, such as adding Tweets to that empty speech bubble on the home page. Now that you have a grasp of the basics, take advantage of the great resources out there to help you with this next step.

Further Reading And Resources

App Design

App Development

  • Learn Objective-C,” Cocoa Dev Central
    A summary of the basics of Objective-C.
  • Cocoa Controls
    Open-source UI components, such as carousels, maps and Twitter aggregators, to integrate in your project.
  • ManiacDev.com
    iOS libraries, controls, tutorials, examples and tools, many of which are open source.
  • Baker Ebook Framework and PugPig
    These enable you to build an interactive book or magazine using HTML5 and then wrap it into an app using Xcode.
  • Creator, GameSalad
    Want to make a promotional iPhone game using drag-and-drop behaviors and your new-found Xcode skills? Then GameSalad’s Creator is for you.

(al)


© James Brocklehurst for Smashing Magazine, 2012.