There are new ways to skin a cat (or navbar) in iOS5

We all want our apps to stand out in the appstore, Apple has provided us with some nice interface elements but the appearance of them is limited. Allmost every company has a corporate design that they want to see back in their app, and even if this is not the case you’ll probably find one of your designers getting a little overenthousiastic with his or her Photoshop skills.

I personally like “custom app” building, I prefer working on something that looks totally different then the rest, creating stuff that makes people say “whow that looks good” and taking some of the designers credit for my own. Having said that I guess we all know this doesn’t (or actually didn’t) come for free. Let’s take the navigation bar as an example.

We want to have give a navigation bar another background image in iOS4 so it fits the overall design better. Easy right? Well.. no. First we create a category on UINavigationBar, use method swizzling to overwrite insertSubview and sendSubviewToBack, we then keep track of the added view with a tag we declare to it and be careful with the placement and removal of the view. We can now set a custom background image to a navigation bar..

Now let’s say we wanted to skin a tabbar or a switch, the solution for this was pretty simple: write your own.

But luckily Apple heard our frustration all the way in Cupertino and actually did something about it: the UIAppearance protocol.

// Setting a background image to a navigation bar in iOS5
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar_bg.png"]  forBarMetrics:UIBarMetricsDefault];

That sure makes our lives a little bit easier doesn’t it?
Let’s do a quick overview of what we can do with this protocol;

We can set an image to UI elements, as the snipped above described for the navigation bar.

We can add tint color to about every UI element, this means navigation bars, buttons, sliders, switches, spinners, activity indicators, etc. So no more custom switch writing if someone decided that the switch should definitely be green.

[[UISwitch appearance] setOnTintColor:[UIColor greenColor]];

titleTextAttributes have been added so we can not only at a custom background image to our bar, but we can also style the title in terms of font, color etc.

[[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], UITextAttributeTextColor, 
     [UIFont fontWithName:@"AachenStd-Bold" size:22], UITextAttributeFont,
     nil]];

Pretty straight forward stuff huh? But it gets better! You can define the scope of your customization.

Let’s say we want to set the background image for all the navigation bars in our project, we would use the code as described above:

// Setting a background image to all navigation bars
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar_bg.png"] forBarMetrics:UIBarMetricsDefault];

But we can also assign the appearance of a particular navbar like this:

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar_bg.png"] forBarMetrics:UIBarMetricsDefault];
// or
[myIBOutletNavbar setBackgroundImage:[UIImage imageNamed:@"navbar_bg.png"] forBarMetrics:UIBarMetricsDefault];

Now let’s sat we wan’t all our switches to have that nice green color, except that one little switch hidden deep down in the third hierarchy of your settings screen, well we can do that as well using +(id)appearanceWhenContainedIn:

// WhenContainedIn takes a nil terminated list of view controllers
[[UISwitch appearanceWhenContainedIn:
[myThirdSettingsViewControllor class], nil]
setOnTintColor:[UIColor redColor]];

Conclusion:

Apple finally provided us with a better way to skin user interfaces, will it be all you need? Probably not, there will still be cases were you’ll have to go the hard way to please your customers or designers, but it’s definitely a big improvement on what we had. At the very least my navigationbar skinning code is easily readable by my co-workers now.

References: UIAppearance Protocol Reference

Category loading bug in iOS

I known this is an old topic, but today I found out a new way that some developers devised to avoid it.

Long story short: the linker tool that Apple provides messes it up when linking a static library containing categories. A pair of linker flags (-ObjC -all_load) has to be provided in order to work around it. The flags instruct the linker to load all the methods (even the ones not being used by that particular application) and collides with some other libraries issuing duplicate symbols errors.

The solution from Apple’s point of view seems to be tricky as it is not being fixed for a long time now, and many developers had opted in for less intrusive fixes (like using the less restrictive -force-load setting) but still requires a big deal of internal knowledge of the tool chain internals.
I read this morning on RestKit development list a new way to deal with it I wasn’t aware of. The original fix was supplied by the developers of the well-known library Three20.

The fix consists in tricking the linker into thinking that the library indeed has some (dummy) implementation code worth using by using the following #define statement:

#define FIX_CATEGORY_BUG(name)
@interface FIXCATEGORYBUG ## name;
@end
@implementation FIXCATEGORYBUG ## name;
@end

They way you apply the code to an existing class category implementation file is like this:

FIX_CATEGORY_BUG(NSData_MD5)
@implementation NSData (MD5)

By using this technique you are not required anymore to use -all-load linker flag, and you won’t get all those annoying errors when linking more than one static library.

References:
Apple Technical Q&A article
Three20 fix
RestKit fix

Forget about retain and release, welcome to ARC (II)

This is the second article on our series about ARC. In the previous one we introduced the basic design concepts behind it, now we will explain a bit in detail which precise methods and features are deprecated from manual memory management and the new keywords and statements we will use with it.

Enabling ARC

As any other compiler feature, ARC is enabled by setting the parameter -fobjc-arc in the compiler settings. If you use the refactoring tool in an existing project, this setting will be added automatically.

Refactoring tool

The refactoring tool removes all the calls to existing methods, converts the lifetime qualifiers for properties and variables, replaces autorelease pool with the new @autorelease statement and every other detail. It worked flawlessly in our tests for most projects, saved some external libraries, so please don’t hesitate to give it a try. In case some code couldn’t be automatically converted, the manual procedure to get it fixed is usually straightforward.

Deprecated methods

As soon as you enable ARC, using any of the following methods will result in a compiler error (this includes the @selector() statements): retain, release, autorelease, retainCount and explicit dealloc invocations (including [super dealloc]). Although not necessary most of the times, you can still implement dealloc to perform other cleanup operations (i.e. canceling pending networks operations) but invoking the super class is not required or even allowed.

Autorelease pools

NSAutoreleasePool objects are not accesible anymore directly from the code. Instead, the compiler provides the new statement @autorelease which performs the same task you used to do before with them. The most straightforward example is main.m:

int main(int argc, char *argv[])
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  int retVal = UIApplicationMain(argc, argv, nil, nil);
  [pool release];
  return retVal;
}

becomes

int main(int argc, char *argv[])
{
  @autorelease {
    return UIApplicationMain(argc, argv, nil, nil);
  }
}

Properties lifetime qualifiers

In the previous memory management model, we explicitly define whether a property retain count should be increased or decreased, or just be untouched when a property is accessed via the dot operator – these are the well-known retain and assign qualifiers. Roughly speaking we just have to replace them by the new strong and weak types. Let me extend a little bit more on what this means.

Lets say we have an existing property defined as:

@property (retain) NSString *text;

The property is synthesized in the @implementation section as usual, instructing the compiler to create the setter and getter methods. Although you never see the code, a typical setter method created by the compiler would look like this:

- (void) setText:(NSString *) _text
{
  [text release];
  text = [_text retain];
}

thus releasing the existing ivar (if it is nil, nothing will happen of course) and increasing the retain count on the passed object. In addition to that, to avoid memory leaks you should instruct the object containing the property to release the previously assigned object at the end of its lifetime, usually like this:

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

There are more way so deal with this (I’m talking about setting the property to nil for example) but those concerns are out of this discussion. When jumping into ARC, it is up to the compiler to deal with these concerns and as a developer you just focus on the relationships between the objects in your application. In this example, you just have to specify that the property is strong, meaning that the assigned object should exist at least during the lifetime of the object containing the property. The code will just be:

@property (strong) NSString *text;

Plus of course the @synthesize directive that creates as before the setters and getters. Well, that by itself will save up not only development time but also debugging problems and leaks. What about the assign qualifiers? Same applies here, code previously containing properties marked as assign will just become weak, meaning you don’t expect for the assigned object to stay in memory during the lifetime of the parent object.

Now let’s go for a slightly more complicated case, please take a look to this code:

self.text = [[NSString alloc] init];

As of previously memory model, this code will produce a leak. Why? The string is created with a retain count of 1, assigning it via the dot operator to the property previously defined with the retain qualifier also increases it becoming 2. When the lifetime of the parent object ends, the string retain count is decreased by 1, but still the object retain count doesn’t reach zero so dealloc is not invoking and we have an unreleased object which lacks ownership (no one can claim or use it, as the reference is lost when the parent object disappears from memory) thus creating a leak. If you happen you have many of those, you’re memory will be exhausted soon and the application will crash.

The way you usually fix this is by either marking the object to be released in the next autorelease pool cycle or just releasing it after the assignment.

self.text = [[[NSString alloc] init] autorelease];

or

NSString *string = [[NSString alloc] init];
self.text = string;
[string release];

ARC is smart enough to insert those by itself by inspecting the lifetime of the object through code analysis. That’s the kind of magic the compiler implements and the nuisances it ’releases’ the developer to deal with. Bye bye leaks!

Variables lifetime qualifiers

We won’t go deep into this, but besides properties and ivars (usually residing on the heap) you will also have variables in the stack frame. The new type qualifiers are used the same way to do with static or const, but in most cases you just want for them to be strong, it’s the case by default. The new qualifiers are __strong, __weak, __unsafe_unretained and __autoreleasing. Lets talk about them a little bit.

The __strong qualifier, the one used by omission instructs the compiler the keep the object in memory during the lifetime of the stack frame, that’s usually the block of code marked by braces. __weak variables are a little bit trickers, as the compiler will get rid of the object in memory as soon as possible even during the stack frame existence. Please note that it also will set it to nil, to avoid crashed on sending messages to dangling pointers.

Similar to __weak is __unsafe_unretained – it will deallocate the object as soon as possible, but it won’t assigned nil to the variable (thus the unsafe part I assume). The exact use case for it varies from function to function but you will find a number of them when interacting with static variables defined somewhere else or Core Foundation toll-free bridge objects.

Finally __autoreleasing will mark the object to be autoreleased when the stack frame is released, this is what we should use for factory functions returning argument references (NSError **error like) and you want them autoreleased on return from the function. Please note that this is not necessary when just returning an object you just creating.

In a nutshell, you won’t have to use these qualifiers in most occasions, as the default one if sufficient for most use cases. Nevertheless be aware the specific behavior or use cases should take them in account if you want your code to work the way you want to.

Other considerations and coexistence

There are some other restrictions you must enforce in order to make you code coexists with the old scheme, name you can’t name properties starting with new, as this is used internally by the compiler. Additionally, if you use Core Foundation  or any other C/C++ based libraries, the following rules apply:

  • CFRetain and CFRelease must be still used
  • Using object pointers in C structures is not allowed anymore
  • No more casting between id and (void *) types

Check the documentation!

Apple currently provides some of the most comprehensive documentation set for their software products. Although ARC is a new product you will find some documentation describing the new features and possibilities that it opens to developers. Please check this link [developer.apple.com] to get an introduction on ARC. This other article [developer.apple.com] on memory management shows a little bit more what’s happening internally. Both of them are a really nice read that gives a good insight on most topics regarding memory and iOS.

Forget about retain and release, welcome to ARC (I)

One of the first things you learn after landing into iOS and Objective C is that garbage collecting (GC from now on) is evil. It is not really evil in itself, but performance wise and specially when facing user interaction you take for granted a few things: scroll shouldn’t shutter and lag must be confined. Your users don’t deserve less than that!

Memory management is tedious, and most interpreted, dynamic languages developers don’t deal with it directly. For C/C++ and most compiled languages developers is bread and butter, but it costs time and effort to get it right, and introduces bugs that tend to appear when a product goes in production. In MacOS X, the Cocoa runtime implements GC for easing the pain of retain and release cycles.

Whereas this approach works for a desktop-size machine, in an embedded system is not that straightforward. As most Android and Java developers will acknowledge GC kicks in the most inconvenient times, usually when the impact on the user experience is most noticeable - when some screen refreshing is triggered. Google is known to have been working on improving this for a long time, but still requires at least some CPU horsepower to minimize it.

Apple decided they wouldn’t be delivering a GC for iOS in the near future. Still, writing memory management code is cumbersome and prone to errors. Their answer comes from the hands of LLVM, the new alternative compiler to GCC that Apple has been working on for the last years. Long story short, it sits between the classical GCC architecture (while flexible, impedes some types of optimizations and makes it difficult to provide feedback to the IDE) and the CLR/JVM compilers targeting virtual machines. The analysis feature of XCode is based on this new compiler and provides developer with the usual catch-ups on memory management, mostly leaks.

I imagine someone asked: well if we could detect leaks with this systems, couldn’t we also fix them? Or even better, track the code paths so that we don’t need memory management at all. Moreover, we won’t need a runtime to do so (á lá GC) so no user experience impact will come from it. And so ARC was born.

First the disclaimer: at the time of this writing, LLVM 3.0 and ARC are only available for iOS5 SDK, so until GM is released you shouldn’t code with it for production projects, as you won’t be able (in principle) to submit code to the AppStore developed this way. But of course you can think of the future and start learning to use it as we are doing here at Sharewire.

During this series of posts I’ll be assuming the reader is familiar with iOS development, memory management and general development background.

So, how does it looks like?

At this point you are sick of writing retain and release cycles, creating autorelease pools for threads and getting sure that the ownership of the objects you create are already there. For more advance programmers, memory zones and zombies are somewhat of a pain. Well, forget about them. The most simple idea behind ARC is just to replace the usual qualifiers for properties (i.e. assign and retain) for strong and weak. This of resembles of some other languages, but in a nutshell you just have to specify whether you would like to keep the object assigned to the property in memory during the life time of the object for which this property is defined.

Additionally, it’s up to the compiler to keep track of the retain count for the objects you create (sort of, as this operation is performed in compile time). Please note that there is no magic behind this, the compiler is just smart enough to add the retain and release operations required to avoid memory leaks. Think of it being the same of synthesized properties: you just instruct the compiler to create the setters and getter, the same idea applies to retain and release cycles. The memory count is still kept but you don’t have to deal with it.

It’s not only that: you can’t manually retain and release objects once the project is enabled for ARC. Nor you are supposed to call the super call dealloc method or even use it.

Autorelease pools is a similar story. The autorelease pools are not created explicitly anymore, but you instruct the compiler (via a new at sign operator) to create and flush them. Really convenient in a sense, but again think of it of a shortcut as the pools still exists during runtime, you just don’t have to deal with them directly anymore.

The last nice thing that XCode adds is the possibility to convert you current projects to ARC – the IDE provides a refactoring tool to fix a whole project to the new scheme, making the whole process painless and quick.

Although I’m leaving things in the drawer, please let me finish this introduction to ARC here. In following articles we will describe in depth how to save up some precious coding time by using this new tool.

Welcome to Sharewire Dev Bits

The first idea about creating a blog like this came in one of our weekly developers meeting. These are the kind of meetings in which you are supposed to talk about your current project, problems you found in them and all that. It’s usually the case that we end up by talking about something really new we just discovered, a groundbreaking tool we could apply to the problem we are trying to solve or just to bash about how bad some development tools are.

Despite of all that chit-chat more often than rarely we find some really nice points, ideas or solutions worth sharing. It didn’t take long for someone to suggest the idea of having an internal blog where people not being able to attend particular meetings, or that just joint the company could look up for the bits we shared in previous occasion, thus the existence of this blog.

The company we work for, Sharewire B.V. is one of the biggest mobile development companies in Europe. What do we do? Putting it as simple as possible: we provide customers (usually in the business to business segment, but also in the casual and commercial one) with full service, meaning we create an specifically-crafted concept (we can be proud to have the best art department I cold wish for), that will be eventually transformed in a tool you can use and enjoy in your mobile device. As simple as that!

Our task as developers is to bring life to those concepts. We target most platforms in the market, ranging from smartphone devices to tablets, passing through web apps and mobile sites. Because of that, we really need to always stay in the bleeding edge of technology, facing challenges most people working in the IT industry don’t deal with. When was the last time you googled for something and couldn’t find a single reference? We do it on daily basis, and man we know how to use Google. Later on, when the problem is solved you really feel like in the mood of telling to everyone you could finally find a fix for the problem that kept you awake at night for two days – and it was just a few lines of code away!

So, if you are one of those who feels the same kind of challenges we do, this is your blog. Also, if you are interested in general mobile technologies, approaches and devices we will also be discussing those. Finally, and in time we also would like to open a space of discussion, support and help for all those sharing our interests, hopes and concerns. Source code will also be part of the deal! That was what the internets were invented for, right?

Follow

Get every new post delivered to your Inbox.