Archive for objective-c

Working with Orientation Changes on the iPhone Part 2

// June 14th, 2009 // No Comments » // iphone, iphone sdk, objective-c, orientation changes, xcode

In my last post I outlined a scheme for working with orientation changes on the iPhone. Sadly, that scheme does not work on iPhone OS3.0 so I rewrote the code to work for OS3.0. You can download the XCode project here: XCode Project

This is a slightly simpler approach and doesn’t rely on any of the SDK code for reorienting things. In some ways you have more control over what you are doing but you have to code the animations by hand. Let me know in the comments if it works for you.

Programming Lessons: iPhone Style

// April 10th, 2009 // No Comments » // 42 restaurants, application, iphone, iphone sdk, objective-c, programming, xcode

I have been really busy, as many of you have noticed, the last few months juggling my job at ChessCube and building an iPhone application. I have even gone so far as to only work for ChessCube part-time in order to make time to build my application.

The application I have busy building is called 42 Restaurants and it was a concept my girlfriend, Margarét, and I came up with one day while sitting in a sushi restaurant. It goes along the lines of producing a really beautiful iPhone application that showcases recipes from some of the best restaurants in the world. You can read more on the 42 Restaurants website here.

The concept started out simple. My knowledge at the time of the iPhone SDK was very basic and we didn’t want to be too ambitious. The main features would be amazing pictures, simple functionality and great recipes; all the while providing good marketing for the restaurants involved.

Now that we are nearing the end of developing the application, I can let everyone in on some tips to hopefully help their progress with their own application.

1. Read, Read, Read

The main thing that stood me in good stead for learning the SDK was reading. I read everything, from the Apple developer documentation to blogs and online tutorials. The two books that really helped me the most were - The iPhone Developers Cookbook By Erica Sadun and Cocoa Programming for Mac OS X by Aaron Hillegass. The best thing about these two books is that the former teaches you how to build and use components in the SDK without needing to worry about things like code structure and development tools. The latter teaches you the fundamentals of Cocoa programming – even though it contains no coverage of the iPhone SDK.

Understanding the basics is key to using the iPhone SDK.

2. Get To Know XCode

Coming from a development environment from Eclipse, XCode seems at first very different and at times a bit clunky. Now that I have figured out how to use a large portion of it, I can honestly say that I love it. Its simple, fast and it isn’t intrusive while you are coding. One tip which I think most Eclipse & Netbeans programmers will appreciate is to change the Layout Mode. Go to XCode->Preferences->General and change the Layout to All-In-One. All your XCode windows will then be grouped into one place and the interface will alter itself depending on whether your are debugging or coding.

Another important thing to do is download all the SDK documentation to XCode. Take a look at this great blog post to see how to do it without having to use XCode’s built-in documentation downloading mechanisms.

3. Understand How Interface Builder Works

From reading numerous forums on the topic, programmers seem to find it difficult to understand Interface Builder (IB). I was one of them. My distrust of WYSIWYG interface tools led me to building all my view code manually. This, as you can imagine, took me forever until I spent some time trying to understand IB. Now, I pretty much build all my components in IB.

The main concept I had difficulty grasping with IB was what piece of code fitted with what. Each XIB file has two parts, a File’s Owner and a View. The File’s Owner is a class that inherits from UIViewController and the View can be any class that inherits from UIView.

If you want to initialize a XIB file all you need to do is instantiate your view controller with the method initWithNibNamed and then add the view of that view controller as a subview of whatever view you are currently displaying. If you want to do any post instantiation initialization, such as setting text for a UILabel or applying an image to a UIImageView then you override the method viewDidLoad in your view controller.

Don’t forget of course to wire up your IBOutlets and your IBActions in your File’s Owner to your View and to set your File’s Owner to be the custom view controller that you have created in XCode. Otherwise, your view will load and nothing will happen.

4. Don’t Do Cut-and-Paste Coding

This seems to be the number one problem in the development community. There are too many programmers that try to code by searching the Internet looking for solutions to their particular problem. Cutting some sample code from a blog or forum post. Pasting it into their project only to find A) it doesn’t work, B) it is full of bugs or C) badly written.

Understand the principles of what you are trying to do before you go on the web to find a solution. Often you will save time writing the component/algorithm from the ground up and even if you don’t, you will have learnt a lot in the process. The next time you have to build something similar you can use that knowledge.

5. Don’t Be Scared to Rewrite Code

My application was about 80% complete when I realized I was coding around my solution. The architecture that I had designed was firstly, very inefficient memory-wise and secondly, limiting me in terms of the functionality I needed to add. When I started the project I had a very basic understanding of Objective-C and the iPhone SDK, and my solution thus far had evolved into a big, code beast. So I spent 2 days rewriting the core of the application. I lost 2 days but I gained a whole bunch of functionality, improved memory usage and reduced my code base considerably.

6. Lessons

42 Restaurants will hopefully get into the App Store at the end of April. Although the idea seemed simple to start off with, it has grown into a fully fledged recipe application. The sheer amount of design work that Margarét has put into it, makes it in my mind, a masterpiece. Each individual recipe has been custom designed and the application is looking amazing because of it. We both wanted to the application first and foremost to blow the user away with how great it looks and I think we are there.

I hope the code-work on my part will live up to the task. Keep watching this blog and the 42 Restaurants website for news on the launch. We are also on the threshold of starting a round of user testing, so if you have an iPhone and would like to check what we have built so far, post a comment and I will add you to my list of testers.

iPhone XML Management

// November 27th, 2008 // No Comments » // iphone, java, JTidy, libxml2, NSXMLParser, objective-c, programming, screen scraping, XML

Learning how to program in Objective-C and for the iPhone can be really frustrating sometimes. Although I am coming to grips with the language and its frameworks, I am finding certain seemingly simple tasks a bit of a chore.

For instance, as one of my own projects to help me learn Cocoa Touch, I am trying to do some parsing of HTML off of a website – screenscraping. To handle any kind of XML processing there are, to my knowledge, only two libraries/utilities you can use. One is the dreaded libxml2 and the other is NSXMLParser.

Firstly, libxml2. What a nightmare! Albeit that it is reported to be very memory efficient and fast, it is written in C, has the most confusing documentation on the planet – and to top it all off, the classes are named according to a different set of coding standards from the ones I am used to. This makes all sample code, that I could find, very difficult to read.

What I did find however, was a couple of utility classes written by Marcus Zarra that makes XPath querying with libxml2 a bit easier. But not easy enough.

Which brought me to NSXMLParser. If you are going to use NSXMLParser to screenscrape you are asking for spaghetti code. NSXMLParser is a SAX-style parser. In other words, while parsing through an XML document it fires events on the start of an element, when it finds characters on an element and at the end of an element. This works very well if you know what the XML is going to look like but it is not ideal when working with HTML.

In the end, after fiddling for a few hours and many curse words I got my code to work with NSXMLParser. Even though it looked like a dog’s breakfast and would probably break the moment an extra tag was added to the HTML.

There is one other thing, however, that you can do, create a proxy for all the data that you send to the phone. This serves two purposes. The first, is that you can use Java running on a web server to fetch, clean and extract the data from the website you are trying to scrape. I used a combination of JTidy and XPath to extract the data I needed from the relevant pages and convert it to objects which I can now serve to the iPhone. This gives an incredible amount of flexibility and allows for a marked improvement in performance as the phone does not need to load large documents into memory in the background.

The other major benefit of using a proxy server is that if you offload processing to an external server, and you make your iPhone application as dumb as possible you won’t need to update and resubmit your iPhone application to Apple, within reason of course. You can even resize images on the server and cache responses.

My application now uses NSXMLParser to work with simple XML files and I have a lot of control. Moral of the story, don’t try and do everything on the phone.

So what’s next? Well I am going to finish my server-side code. Rewrite my iPhone application so that it works with the simpler XML from the server. Once all this is done I can start working on the more fun parts of my application, such as using the media frameworks for the iPhone namely the camera, video and audio.

Objective-C: Tips for a Java Programmer

// October 12th, 2008 // 7 Comments » // instruments, iphone, iphone sdk, java, java objective-c comparison, key-value coding, learning, objective-c, programming, xcode

I have been learning Objective-C part-time. Partly to learn something new and different but also partly out of curiosity. As a Java programmer, I initially thought it would be a doddle but as soon as I looked at the code I realised it was going to take a bit of getting used to. After going through Apple’s excellent, yet verbose, guide: The Objective-C 2.0 Programming Language – I started to get used to the syntax. Its not that hard, especially if you come from a C or Java background. Here are some of the differences and some of the highlights I have encountered so far.

1. Methods, Functions, Messaging

The most difficult thing to get used to initially is the syntax for calling methods, or as its called in Objective-C: messaging. In Java calling a method on an object looks like this:

Car car = new Car();
car.drive(10, 100);

This piece of code creates an instance of type car and then tells it drive 10 kilometres at 100 kilometres and hour. If we were to write the same thing in Objective-C it would look something like this:

Car car = [[Car alloc] init];
[car drive:10 speed:100];

Whoaaa! Hold on a minute. That is completely different from Java and C. Well, don’t panic. If you have ever programmed with C or C++ you will probably understand the first bit – Car *car. We are creating a pointer to a place in memory that holds a car. The part after the equals is a little more confusing. The designers of Objective-C have dropped the dot-notation completely for messaging objects. The piece of code [Car alloc] can be rewritten in Java as Car.alloc(). In Objective-C, this is the way to allocate a piece of memory for your instance. It is also the way you call methods on instances.

The closest equivalent to a constructor that I can find in Objective-C is the init message call. All objects have an init method – inherited from the base object NSObject (in Java this would be equivalent to Object). You can override the init method in your classes to add initialisation code.

So the first line in our example now makes sense, but what about the second line? Objective-C uses the concept of named arguments. This may seem redundant or a little verbose, but once you get used to it, it does make it easier to read. This syntax scheme is an adaptation of the way you would message objects in Smalltalk. So we are basically messaging our instance of car to drive 10 at the speed of 100. I could have possibly made the method a little more informative and written it as: [car driveFor:10 speed:100].

2. Garbage Collection vs. Retain Counts

Since Mac OS X 10.5, Mac developers have been treated to the simplicity of writing code without having to worry about memory management – in other words, Garbage Collection has been introduced. The only thing to bear in mind is that if you want to write code that is supported by older versions of Mac OS X, namely, 10.4 and the iPhone you will still need manage your memory manually. Fortunately, detecting memory leaks is fairly simple with the Apple developer tool Instruments.

The mechanism by which you manage memory manually is called retain counts. Every time you make an object point to another object you increase that object’s retain count. This loosely means that if you have 10 pointers pointing to an instance, the instance will have a retain count of 10. Whenever you are finished with a pointer you need to release the object. This drops the instance’s retain count by 1. When an instance’s retain count reaches 0 it will be deallocated.

There are many pitfalls with manual memory management. Having a memory leak means that over time your application will consume more and more memory and it will crash the system eventually. There are 2 main ways you can create a memory leak. The first is to have an orphaned object. This is where the object has a retain count greater than zero but there are no other objects pointing to it. The other is to have a retain cycle. This is where Object A points to Object B and Object B points to Object A, and nothing else points to these two objects.

If you want to build applications for the iPhone or for older versions of Mac OS X then you need to be more meticulous with your code. Make sure that your objects always clean up after themselves and use the application Instruments to ensure you have no memory leaks. On the iPhone memory leaks can be disastrous, since you only have a very limited amount of memory to play with. Should your application run out of the allocated memory on the iPhone, it will reboot – basically quit your application.

3. Cool Extras

Objective-C has some really cool features built into it and some downright weird ones. Two really cool features that have no equivalents in Java are: Key-Value Coding and @synthesize/@property directives.

Key-Value Coding is a very neat and dynamic way of querying objects by name. Some people would say that you can do similar tricks in Java with Reflection but Key-Value Coding has a lot more useful features that you cannot leverage in Java without writing a lot of code.

Key-Value Coding works like this:

Car *car = [[Car alloc] init];
[car setValue:@”BMW” forKey:@”carMaker”];

Basically, we are setting the value for the property carMaker to BMW. This seems cumbersome, but bear with me. We can now retrieve the value in the following manner:

NSString *carMakerString = [car valueForKey:@”carMaker”];

We can now read and set objects by their values. The cool thing is that you don’t need to cast any values. The valueForKey method will automatically cast the value for you. Programmer’s used to dynamic languages will probably laugh at the significance of this but if you are from a Java background you will appreciate not having to check and cast the result of the call.

You can also describe keypaths for key-values. A keypath is basically a way of navigating a pointer graph to a property from object to object. For example:

NSNumber topSpeed = [car valueForKeyPath:@”carMaker.topSpeed”];

Where topSpeed is a method that returns an int for the car’s top speed. The int will be auto-boxed to an NSNumber at runtime.

In addition to keypaths, there are also aggregator functions you can use on key-values in arrays. So for instance, if we have an array of car objects and we want the average top speed of all the cars at the BMW dealer we could do the following:

double averageSpeed = [bmwDealer valueForKey:@”cars.@avg.topSpeed”];

If we wanted to something similar in Java or without key-values we would have to loop through the whole array of cars, add the top speeds to a variable and then divide by the number of cars in the array. If you want to learn more about Key-Value Coding, including the most powerful feature for binding values, called Key-Value Observing, check this article out.

Another cool feature that Objective-C contains, that I use all the time are the @property/@synthesize preprocessor directives. The combination of these eliminates the need to write boilerplate getter and setter code. The @property directive, used in the header file for a class, tells the compiler that this is a property of the class. In addition you can make the property read only or readable/writable, by adding read or readwrite in brackets like this:

@property(read) int topSpeed;

Or,

@property(readwrite) NSString carMaker;

You can also tell the compiler how to manage the memory for the getter and setter of that property by putting a retain, assign or copy after. Like this:

@property(read, retain) NSString carMaker;

By adding @synthesize in your class file for your properties. The compiler will automatically generate getter and setter methods for you.

@synthesize carMaker;

4. So Far, So Good

So far my experiences with Objective-C have been favourable. I do get confused sometimes when my code won’t compile and it looks correct, only to realise that it would be correct in Java but will never work in Objective-C. Apple’s Interface Builder software is top notch and makes designing and hooking up your interface very simple. XCode’s code editore on the other hand, in my opinion, is a bit behind compared to Eclipse. A Mac developer would, however, probably class Eclipse as bloatware. Instruments is my favourite and makes optimising your application and finding memory leaks a doddle.

Helper Objects

// September 28th, 2008 // No Comments » // coding style, mac osx, objective-c, programming

I think this is a brilliant comparison between using Helper Objects and Sub-Classing:

Once upon a time (before Baywatch), there was a man with no name. Knight Industries decided that if this man were given guns and wheels and booster rockets, he would be the perfect crime-fighting tool. First, they thought, “Let’s subclass him and override everything we need to add the guns and wheels and booster rockets.” The problem was that to subclass Michael Knight, you would need to know an awful lot about his guts so that you could wire them to guns and booster rockets. So instead, they created a helper object, the Knight Industries 2000, or “KITT the super car.”

Note how this is different from the RoboCop approach. RoboCop was a man subclassed and extended. The whole RoboCop project involved dozens of surgeons who extended the man’s brain into a fighting machine. This is the approach taken with many object-oriented frameworks.

While approaching the perimeter of an arms dealer’s compound, Michael Knight would speak to KITT over his watch-radio. “KITT,” he would say, “I need to get to the other side of that wall.” KITT would then blast a big hole in the wall with a small rocket. After destroying the wall, Kitt would return control to Michael, who would stroll through the rubble.

Bits, Bytes & The iPhone SDK

// September 5th, 2008 // No Comments » // iphone, mac osx, objective-c, programming

So I’ve been toying with the idea of building an application for the iPhone and yesterday I finally decided to download the SDK. After agreeing to give my soul to Apple as stipulated in their Terms & Conditions and 8 hours of downloading later I finally got the full SDK.

I have been trolling through their documentation and it looks like I will have to get my hands dirty in Objective-C. Which, from what I can tell, is a slightly cleaner version of C++ specifically designed for Mac OSX. In case you didn’t know, the iPhone runs on a heavily modified version of the Mac OSX kernel. This has its benefits in that by learning to program for the iPhone I will also slowly become accustomed to writing programs for Mac.


The easiest way to learn a programming language is to remember that they are all essentially the same. Don’t get confused between a programming language and a markup language. I can’t tell you how many times I have read on programmer resumés that HTML is a programming language. HTML is a markup language – a way of describing visual data in a hierarchical textual fashion. A programming language is a set of statements that can be executed sequentially and all procedural programming languages follow a similar set of rules and contain 3 specific constructs:

  1. Variables
  2. Conditional statements
  3. And Loops

With these three constructs it is possible, with great pain I might add, to build any program.

Of course a programming language is of no use if there is no way of interpreting it. Way back in the days before Microsoft and Apple, programs were created on punch cards – pieces of cardboard with rows of holes punched in them. Every hole represented a 1 and every non-hole represented a 0. The punch cards were fed through the computer which would read the rows sequentially and then execute them. Punch cards are so old they were first used back in the 18th century to control weaving looms and were used up until the last century still.

So-called ‘modern’ computers work in much the same way. High-level programming languages such as C++ and Java are compiled by another piece of software, called a compiler and converted to what is known as Assembly Language. Assembly language is a low level language used to program hardware, such as your computer’s CPU. Assembly code is then converted to what is known as Object Code. Object Code is the final sequence of 1s and 0s – the holes and non-holes on punch cards.

Every single computer program you use is constructed in this way. So next time you get the dreaded ‘blue-screen-of-death’ or your e-mail application crashes, just remember how many 1s and 0s are moving through the system. A modern car consists of approximately 12000 parts. Microsoft Windows XP consists of approximately 1 billion lines of code and it works 99% of the time. That is absolutely incredible!

I guess what I am trying to say here is that learning how to program within the iPhone SDK and learning Objective-C is trivial compared to building an operating system like Mac OSX or programming a computer’s CPU. It’s made even easier if we remember that all procedural programming languages are constructed out of similar building blocks and that if we learn and understand the basics of a subject we can go on to learn just about anything.