Our DNA is written in Objective-C

Category Archive for ‘Recipes’ rss

NSNotifications and Background Threads

I’m coming out of highly concentrated work (approx 87 hours) on my latest project. It’s an app that allows you to organize a betting pool for the upcoming FIFA World Cup.

The simplest method of communicating with our web-based API we found to be having the server send array or dictionary PLISTs which I could load and parse in a single line of code synchronously. So first I created all the API calls in synchronous blocking mode. When they where working I added a method by the same name prefixed with “async” and would have the blocking code executed on an NSOperationQueue.

If the synchronous method needed zero or one parameter then you can use NSInvocationOperation of calling it and have the queue work it off in the background. In some cases more than one parameter has to be passed. Here an NSInvocation has to constructed with multiple parameters, which I explained previously.

Once the API call is done processing it needs to tell the app about its result. This is done conveniently by sending NSNotifications. And in all the places in the UI where specific notifications should have an effect, you simply subscribe to the notifications by adding an observer for them to the default NSNotificationCenter. NSOperationQueue automatically uses multiple threads and takes care of the autorelease pool. So any operation might either run on the main thread or on a background thread.

Warning: Crash Ahead!

This causes a problem I have only ever seen happen on Simulator, so I’m not sure if it would also happen on the device. Generally you want the NSNotifications to be sent on the main thread as well, especially if they trigger UI activities like dismissing a modal login dialog. I don’t know if Apple will tweak NSNotificationCenter to send on the main thread in the future, but until they do, here’s my drop in solution.

Read more

BSA Banner

Parsing an RSS pubDate

Andreas Heller asks:

When parsing an RSS feed I get a date from pubDate, but as NSString and not NSDate. How do I get a date that I can use for sorting?

That’s a problem you face quite often when dealing with dates which are encoded in XML, be it an RSS feed or any other XML-based file format that you would be getting via HTTP GET. Contrary to other languages where any properly formatted date can be automatically parsed we have to do this ourselves in Cocoa.

Fortunately there is the NSDateFormatter class which can do it both ways: from date to nicely-formatted string as well as the other way around.

Let’s do like a Unix-pro and get ourselves some test data by getting some pubDates from my RSS feed. In terminal type:

curl www.drobnik.com/touch/feed/ | grep pubDate

This gets us the pubDates from the 10 latest articles on my blog. We see that WordPress encodes the pubDates in this format “Mon, 03 May 2010 18:54:26 +0000”, not really a very easy to parse one I concede. According to the RSS 2.0 spec this is supposed to be in RFC822 standard. If anyone would ask me, personally I think that the inventor of this date format should be poisoned, then hanged and maybe shot for good measure. Who in his right mind would create a date representation that does not allow for string sorting?

Read more

Meta-Calling Multi-Param Methods

Objective-C has several powerful methods of working “Meta”. Besides of handling methods and objects themselves you can also save a method’s signature in a variable, and call it later. That’s a “selector”. Or you could construct an object representing the entire call of a method, including one or multiple parameters and then use this object in place of the actual call.

Why would one do such a complicated thing? Well, there are several pretty useful scenarios where it is useful to know this technique. The main benefit of this method is that you can construct method calls during runtime using information that you only get while your app is running.

Read more

Physics 101 – UIKit app with Box2D for Gravity

Personally I was most at the edge of my seat at the “Voices that Matters Conference” in Seattle when Rod Strougo showed us how to make a physics-enabled game with Cocos2D and Box2D in under an hour. It really was as sexy as he sounds. Eros did what every good TV-cook would do, he had most things already prepared. On the flight home I wanted to see if I could just take the physics part (without Cocos2D) and make a UIKit app with it.

The goal of this experiment was to have a UIView with multiple square subviews of different sizes that would start falling as soon as the app starts. The first tricky part is how to add the latest version of the Box2D physics engine to your iPhone project. Then we need to mediate between the different units and coordinate systems of UIKit and Box2D. Finally when we got it all running, we also want to add  the current gravity vector to affect the boxes.

Read more

Making Your Own iPhone Frameworks

Previously I explained how to make a static library that simultaneously supports multiple different CPUs. At that time I was ignorant to the reason why there are no means to make iPhone frameworks. But I did not give up searching, especially since apparently a few individuals seemed to have pulled it off without properly documenting their method for others to duplicate.

The only guide I found is from two years ago, but I was able to verify that it works and so I will document it in an article so that many more people can use this great mechanism. But first, let’s briefly explore what it really IS that Apple does not want us to do. The generic statement that you can read on thousands of pages is “Apple does not want you to make iPhone frameworks”.

But is that really so? It turns out, this statement is not entirely accurate or rather specific enough to be the truth.

Read more

Universal Static Libraries

For some reason Apple reserves the ability to create iPhone frameworks for their own use. They are a very useful ability to have because they package headers together with a universal binary. „Universal“ meaning that you get binary code for multiple platforms rolled into a single file. Frameworks are also dynamically loaded which means that less binary code fills up your memory as only stuff is put there that is actually needed.

But alas, no frameworks for us.

Until now I am selling my components in the Dr. Touch’s Parts Store as source code which at the same time means that I could not provide demonstration versions to try out in your own code. If you have the code, what incentive is there to pay the price?

It has been suggested to me by several people independently to make a static library to solve this problem. Could be time- or otherwise limited, but then people could try the parts out and see how well they fit with their own work.

Also next to still offering access to my repositories at full price, I could be selling indidual versions without right to upgrade to get started at a substantial discount. Later if you find that the component really IS worth what I am asking for, you could upgrade to the lifetime upgrade plan via the SVN repo.

Another reason to figure out this Static Library Magic is so that I can bundle my own utility classes that I keep adding to and improving in a central place. This gives me the choice of adding an external SVN reference or to simply copy the static library into my new projects.

In this article I am describing how to create a universal static library for both Intel and Arm architectures, how to glue them together into a single file and how to add it to a new demo project.

Read more

How to Shrink Cells

When you look at the Contacts.app you see that Apple somehow manages to change the size of cells in UITableViews of grouped styling.



If you search around on the internet most of the solutions getting such a look revolve around making your own UIView and adding this as headerView to a section. Now if you want the cell on the right side to still behave like a cell is expected to behave then you have lots of work ahead of you. So I consulted the twitterverse and here props have to go to Jason Terhorst who hit the bull’s eye:

If I recall correctly from Apple’s example code, they just clear the background, and redraw that rounded rect at new size. It’s been a while since I did this, but I think I swapped in my own custom backgroundView.

I researched and experimented for a day to get it perfect. What follows is a description of how to pull off this magic trick, so you can do so too. The end result will look like this:

(Heart Icon by DryIcons)

Read more

Making a Control

At times you may find that you need a control that has not yet been provided for you. In my case I needed a star rating control for iWoman. Ladies will be able to star their love encounters. And the way how such a thing is done nowadays is via selecting between 0 and 5 stars. (If you now ask me to rig it such that your girl can only rate you with 5 stars, then I’ll bitch-slap you)

So I decided to make a UIView that would take UIImages for empty, half-full and full stars. Also I wanted to have some customizability like different numbers of stars and to be able to turn half-full stars on and off. That’s where I created multiple properties so that these values can be set from outside the instance. The steps are always: instance variable (“IVAR”), @property, @synthesize and if the property is a retained object then a line in dealloc.

I made this YouTube video to give you a demonstration and guided tour of DTStarRatingView.

Read more

Stuff you learn from reverse-engineering Notes.app

I’m adding note taking to iWoman 2.0 and so I was thinking which metaphor would be one that users would understand and like. So I decided to mimic the look and feel of the built-in Notes app.

There where quite a few interesting things I had to learn and figure out and in this article I am going to share them with you. These are techniques that you can use in many other scenarios besides of making your own Notes view controller.

I was clear from the start that I needed to use a UITextView for the editing itself. Notes.app has several specialities that we have to figure out if we want to capture the look.

  • Font is Marker Felt Thin, Size 19.
  • each line sits on top of a grayish blue horizontal line
  • the text view has a padding at all sides, something that the standard UITextView does not give us
  • There is padding at the top, but still the text goes up to the corner
  • the horizontal lines move together with the text and never end towards the bottom
  • two static vertical brown lines line up with markings at the top and the bottom
  • the body of the notes is not just a yellow gradient, but has some structure and speckles
  • scrolled text disappears behind the images for the top and bottom edge
  • The text view needs to be dynamically resized when the keyboard appears or disappears to prevent hiding of text.

Those where the challenges, in this YouTube video you see my solution and an overview of how I achieved it. More in-depth reasoning you find below.

Read more

Filtering Fun with Predicates

Being present longer than iPhone OS exists on the Mac platform NSPredicate was only introduced to us iPhone developers in Version 3.0 of the SDK. They have multiple interesting uses, some of which I am going to explore in this article.

You will see how you can filter an array of dictionaries, learn that the same also works for your own custom classes. Then we’ll see how to replace convoluted IF trees with simple predicates. We’ll explore how to use predicates to filter entries of a table view and finally peek into the inner workings of predicates.

Being simple and powerful at the same time it took me 3 hours to write this article. I hope you don’t give up halfway through it, because I promise it will be a great addition to your skillset as iPhone developer.

Read more