learning objective c a ruby analogy
Learning new programming languages is fun. And if it's your 2nd, 3rd...Nth programming language you will eventually look for features you already know and love.
Coming from Ruby - but after having done my fair amount of Java for many years, among other things - I end up looking for features like blocks, open classes and syntax sugar like automatic generation of attribute accessors. These are hard to let go of.
Having decided to learn Objective-C recently, I was delighted to find out that all of these are available - for better or for worse - and wanted to share this analogy with its Ruby counterparts.
- Attribute accessors
In ruby, this class definition
implements for you the getters and setters of the instance variable name.
In Objective-C, the combination of the @property and @synthesize directives provides you with roughly the same result:
Now the compiler is responsible for writing those getters/setters for you.
- Open classes & blocks
Blocks in ruby are the structures that allow you to - among other things - iterate over arrays like this:
Objective-C doesn't have an 'each' method in its root array class (NSArray) but since it does support blocks and open classes, you could just write it yourself:
Yes, I know the syntax isn't appealing, but using it in your program is a bit better:
Given the syntactic differences, the code above is very similar to its ruby counterpart. Iterating over an array is just one of the many things blocks are useful for. Others might include dealing with files, network sockets etc...
Blocks are powerful structures and are not created everyday, but it's nice to know that you can resort to them when the time comes. ;)