Posterous theme by Cory Watilo

Stuck

Have you ever been ‘stuck’, not able to make progress in life, not able to reach towards your goals, no matter how hard you try? Knuckling down, grit, and old fashioned hard work don’t seem to work any more – the words ‘just do it’ seem a distant insult?

What about the other way around: have you ever tried to get someone moving, but no matter what, they just don’t seem to make any progress. No amount of ‘Just do this!’ makes any difference whatsoever. They’re like a car stuck up to the axle in mud. No matter how hard you push or pull, they’re simply stuck: the mud sucking them inevitably down.

Well, here’s a different perspective: why not lift them up? Horizontal efforts will only get them further stuck. You’re simply playing a game that the mud will always beat you in, there. But vertical efforts – now that’s when mud can’t win.

Horizontal efforts: those encouraging, well meaning, but almost nagging urges to ‘just do something with your life’ simply cannot win, because the core issue is the mud: the person’s thought that ‘i cannot win’, ‘i’m a failure’, ‘this is an unbeatable situation, i can’t win’. These thoughts put up a wall that this kind of encouragement simply cannot penetrate. And hence the mud of negative thinking wins the day.

But what if, instead of fighting the mud on its own terms, you cut it off at the knees? What if you speak life into that person? How about: ‘i believe in you’. Or try this one: ‘you’ve got what it takes to beat this problem’. Words like these are so rare, and so powerful. Negativity will fade away in the face of consistent positive words being showered over a person. So – be the leader, shower those positive words.

And the beauty truly is that once the negative mud has cleared from someone’s life, you don’t really need to push all that hard any more, they’ll have all the traction they need to turn their own wheels and get moving just fine.

So next time you’re trying to push someone, how about trying to lift them up instead. You might find that in doing so, you’re solving the root issue, and the symptoms will simply take care of themselves.

Dead easy singletons in Obj-C

Simply declare your class in your header file like so:

@interface MyClass : NSObject

+ (RecordingsMgr*)instance;

@end

Then in your .m file, declare the instance function like so:

@implementation MyClass

+ (MyClass*)instance {
    static MyClass* _myClassInstance = nil;
    if (!_myClassInstance) {
        _myClassInstance = [[MyClass alloc] init];
    }
    return _myClassInstance;
}

@end

Then, whenever you need the instance somewhere, get it like so:

[[MyClass instance] someInstanceMethod]

Beautifully simple, and no mucking around with app delegates, it’ll simply get created whenever first needed. Not thread safe, however, so stick to the main thread.

Update

If you’re concerned about thread safety, you can use this technique:

http://cocoasamurai.blogspot.com/2011/04/singletons-your-doing-them-wrong.html

JSON vs OCON (Objective-C Object Notation)

I’m here to propose another alternative to JSON, Messagepack, Protobuf, and all those other data-transfer formats which are, frankly, about to be made redundant by the introduction of a elegant, concise, and eminently readable format called OSON: Objective-C Object Notation (pronouced O-son).

Here’s an example piece of JSON from their website, quite an ugly piece of work isn’t it?

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

Now, let me fix that for you:

[NSDictionary dictionaryWithObjectsAndKeys:
    [NSDictionary dictionaryWithObjectsAndKeys:
        @"file", @"id",
        @"File", @"value",
        [NSDictionary dictionaryWithObjectsAndKeys:
            [NSArray arrayWithObjects:
                [NSDictionary dictionaryWithObjectsAndKeys:
                    @"New", @"value",
                    @"CreateNewDoc()", @"onclick", nil],
                [NSDictionary dictionaryWithObjectsAndKeys:
                    @"Open", @"value",
                    @"OpenDoc()", @"onclick", nil],
                [NSDictionary dictionaryWithObjectsAndKeys:
                    @"Close", @"value",
                    @"CloseDoc()", @"onclick", nil],
                nil],
            @"menuitem", nil],
        @"popup", nil],
    @"menu", nil];

Much better! ;)

In defence of Objective-C

An unashamed apologist’s perspective on the loveliest language i’ve worked with.

I’ve worked with a lot of programming languages in my time. Not a huge number, mind you, but enough that i can say that i’m open minded and seasoned about it. And, as they say: ‘Don’t feed the trolls’ – well, i’m about to do exactly that: feed the trolls at work who love to rag on about how awful obj-c is! So here i go, foolishly treading where no sensible man dares go: justifying why i love obj-c.

Ugly?

But it’s so ugly! Brackets!

This one is a fair point. Brackets aren’t the most beautiful thing in the world. However – you must appreciate that C++ / Java / C# style syntax isn’t the be-all and end all in this world, and be open minded enough to not reflexively storm out of the building whenever some obj-c code appears on your screen. Go and look at some Lisp, then come back – obj-c will suddenly look better :)

Trust me, it grows on you. You’ll soon learn to see through the brackets – just like the green vertical text in the matrix, it becomes invisible after a while.

Verbose?

You have to type how many characters to format a string? What the – named arguments?

A lot of people see two snippets of code and start worrying:

NSString *formattedString = [NSString stringWithFormat:@"I am %d more verbose than X language", someVerbosityMeasure];

Well, yes, string interpolation is verbose. But really, it’s only NSString stringWithFormat vs String.format which isn’t that big a deal.

People think that obj-c is verbose when they take a superficial look at the language, especially the named arguments. But if you look deeper you’ll find some things are beautifully succinct. For example, to filter an array is lovely:

filteredArray = [allRecords filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"someField == %d", someFieldFilterValue]];

Also, in the bigger picture, you’ll find that the structural verbosity of languages like Java is missing. Things like factories, adapters, and other design patterns are all thankfully not there.

Function calls look weird!

So, when I call a method, which part is the method name? And which is the parameter?

Named parameters will confuse you if you haven’t seen a language with them before. Luckily for me, I used to be a Ruby hipster back in the day so this didn’t throw me, but I can understand the confusion for Java/C# types. So, you’re used to something like this:

myInstance.doSomethingWithParameters(a,b);

And it all makes sense. Things are ordered neatly: the instance you’re calling the method on, then the name of the method, then the parameters. All in that order, as God intended. And then some punk throws the following obj-c snippet in your face, and its just wrong:

[someInstance doSomethingWithObject:a andAnotherParam:b];

Have a look – we’re half way through the method name, then we decide to drop in a parameter (a), then keep going with more method name stuff, and then another parameter. It’s all mixed up. Yes, I can see how this is confusing. So here’s what’s going on:

  • The instance you’re calling the method on is ‘someInstance’, because it’s the first thing inside the brackets
  • The method name is ‘doSomethingWithObject:andAnotherParam:’, the parts to the left of the parameters
  • The parameters are ‘a’ and ‘b’

If you hate this, simply realise that it is just a matter of taste. And think of the huge benefit: You get named parameters, which means your code will be easier to read later on, when you have to debug it.

Memory management

You’ll have to prise my garbage collecter out of my cold, dead hands!

Another common dread is memory management. Most people thought they’d seen the last of that when they moved to Java/C#. And to be honest, it is difficult to think of any other modern languages that still don’t handle your memory management for you. But here’s the rub: obj-c isn’t modern: it’s been around since the 80’s, pretty much unchanged. So it is a bit old, but I like to think it is old like an aged wine.

Keep in mind, the original iPhone had a 400mhz processor with 128mb of ram. The specs pretty much ruled out garbage collection for the sake of a smooth user interface. There’s a philosophy here: user happiness is prioritised over developer happiness. You may not agree with the philosophy, but at least you must understand their point of view.

Having said that, in practice memory management in obj-c becomes simple enough with some experience:

  • It’s reference counted, which makes life a lot easier than C style malloc/free.
  • Autorelease pools make returning allocated instances convenient.
  • Retain properties, and setting them to nil in your ‘dealloc’ means you should never need write a retain/release statement.
  • ARC in Xcode 4.2 should take care of 99% of your concerns automatically.
  • Profiler/Instruments is a great way to find any memory leaks.

One more thing

Obj-C was born in the 80’s, when programming was simple. The architecture astronautitis (Java) that is all too common these days was nowhere to be seen, and it shows. It is the simplest possible OO layer on top of plain old C. Pragmatism rules the day in a lot of the design decisions, and i’ve found it is a great language for Getting Stuff Done, if not in the prettiest way possible. I like to think of it as a simple, reliable old car that just keeps going.

Update the MessagePack objective-c library to support packing

I’ve updated the MessagePack objective-c wrapper so that you can now pack, not just parse data on the iphone. Hopefully some people will find this useful! Basically it works like this:

Parsing Usage

#import "MessagePack.h"
...
NSData* myData = ...
NSDictionary* parsed = [myData messagePackParse];

Packing Usage

#import "MessagePack.h"
..
NSData* packed = [someArray messagePack];
NSData* packed = [someDictionary messagePack];

Here’s the link: https://github.com/chrishulbert/msgpack/tree/master/objectivec

Icons

From a conversation i was having lately with a guy about an app:

Its the small things like a slick icon that makes all the difference
for your app. You want, for instance, my co-worker to walk past my
desk, and for your app's fancy icon on my phone or in my mac's dock to
catch his eye.

He'll ask "what's that app" and then you've got word of mouth
marketing right there.

It's actually happened to me before - it's important for us developers
to simply put some effort into our designs.

How to host a site on Amazon AWS S3, step-by-step

This is a collection of tips and tricks I learnt whilst setting up a static site hosted on Amazon S3 lately for one of my apps. Now, in all the instructions, make sure you replace ‘mywebsite.com’ wherever you see it with your applicable domain of course :)

Buy your domain

First buy your domain (not hosting). This should cost $10/year roughly. People recommend godaddy, but i went with unlimited-space because they didn’t charge extra for WHOIS privacy. However, they don’t supply DNS hosting, so you have to set that up separately.

DNS

Go to zerigodns.com and grab an account. Go into the DNS management and create a new domain: mywebsite.com.

In this domain, create two hosts, one with an empty subdomain, and one with a ‘www’ subdomain. The setup for these two entries should be as follows:

mywebsite.com
Type: A
174.129.25.170 

www.mywebsite.com
Type: CNAME
www.mywebsite.com.s3-website-us-east-1.amazonaws.com

The IP address against the ‘A’ entry is used so that anyone who forgets the ‘www’ gets send to wwwizer (a free service that requires no account), who will forward them to the ‘www.mywebsite.com’ which will properly forward them to S3.

Unless you bought your domain from someone who packages it with DNS hosting, you’ll need to connect your domain registrar with zerigo. You’ll have to go to your domain registrar (ie unlimited-space in my case) and set your nameservers to:

a.ns.zerigo.net
b.ns.zerigo.net
c.ns.zerigo.net
d.ns.zerigo.net
e.ns.zerigo.net

S3

In the AWS S3 console, make a new bucket called ‘www.mywebsite.com’. Right click > Properties on this bucket, and set up the following:

Bucket policy

In the ‘Permissions’ tab, edit the bucket policy to make it publicly readable. Set the bucket policy as per on this blog on ariejan.net, as follows:

{
  "Version":"2008-10-17",
  "Statement":[{
    "Sid":"AllowPublicRead",
        "Effect":"Allow",
      "Principal": {
            "AWS": "*"
         },
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::www.mywebsite.com/*"
      ]
    }
  ]
}

Make sure you replace the ‘www.mywebsite.com’ above to match your s3 bucket name.

Website

In the website tab of the bucket properties, select ‘enabled’, put in index.html as your index document, and `error.html`` as your error document.

You will see the endpoint in this tab as well. It should look like www.mywebsite.com.s3-website-us-east-1.amazonaws.com. Just double check that it’s the same as the CNAME entry you made in your DNS settings.

That should be it! You’ve now got a static website for a fraction of the price of typical hosting. My rough calculations indicate that this should cost me ~$2 a year. Brilliant.

Drawing a textured pattern over the default UINavigationBar

Say you want to draw a cool looking navigation bar, say with a slightly transparent pattern that is overlaying the default look of the nav bar, here’s how to do it.

Firstly, create a subclass of UINavigationBar:

#import "MyNavBar.h"
#import "QuartzCore/QuartzCore.h"

@implementation MyNavBar

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    UIImage *img    = [UIImage imageNamed:@"MyTextureFile"];
    CGContextSetAlpha(UIGraphicsGetCurrentContext(), 0.05);
    [img drawAsPatternInRect:CGRectMake(0, 0,
        self.frame.size.width, self.frame.size.height)];
    CGContextSetAlpha(UIGraphicsGetCurrentContext(), 1);
}

@end

Then, in your main XIB where your nav bar is declared, overwrite it’s class to be ‘MyNavBar’. That’s it!

The beauty of this technique over method swizzling or categories is that it allows your drawrect to call the original (super) drawrect, so that you can simply add a texture ‘on top’, instead of having to draw the gloss yourself.

Markdown Presentations

I’ve been giving the occasional presentation at work and just wanted a way of making quick and simple presentations in markdown, as opposed to mucking around in powerpoint for hours. So came about this project of mine: Markdown Presenter.

To make a presentation, you format your markdown file as normal, with slides separated by an ‘!’ paragraph, as below:

My story
===
* Wasted +1yr on first app
* ...

!

Sales
===
* Money's kinda useful
* ...

!

Coding
===
* Obj-C is nice
* ...

To see an example presentation, see here.

Note that you’ll have to host the files on a web server, because of the way it loads the presentation via ajax. All this is explained on the github page. Hopefully for someone it’ll save some time next time they want to whip up a presentation!