2

Objective-C

Posted by jason on Jun 11, 2009 in Objective-C, iPhone

Here are some interesting things I learned today about the differences between java/C# and Objective-C.  Also how to play a sound on your iPhone.

Calling Methods

This was the very first thing that jumped out at me when I started using Objective-C.  To call a method, you use the following syntax:

[object message:param1 namedParam2:param2 namedParam3:param3];

You can call a property by using a more familiar dot notation though.

[object setProperty:value];
object.property = value;

Those two lines of code are equivalent.  Even though the brackets are awkward to me, I really love the fact that it has named parameters.  You always read in your code what the heck it is you are passing in.  I love this feature.  I wish java and C# both had this feature for the readability of the code alone.

[Update: 6/11]

Thanks to Martin for pointing out to me that these are not actually named parameters.  The order matters and the parameters help make up the function name.  I confirmed this for myself by writing the following two functions.

- (void) play:(id)x withDuration:(id)y withVolume:(id)z
{
    // 
}

- (void) play:(id)x withVolume:(id)z withDuration:(id)y
{
    // 
} 

These are two different methods.  They have the names “play:withDuration:withVolume” and “play:withVolume:withDuration”

Garbage Collection

This one is interesting to me.  Objective-C supports garbage collection the same as C#.  The unfortunate thing is that it is only supported when developing for the Mac.  It is not supported on the iPhone.  When programming for the iPhone, you have to worry about memory management like you did back in the old days.  This means you have to concern yourself with error prone reference counting with methods “release”, “retain”.  This has been the cause of many bugs in the past and could cause your app to suddenly quit unexpectedly if you aren’t careful with memory leaks.  The confusion usually was around who was responsible for freeing an object.  Was it the library or the calling object?  Fortunately, Apple has a firm policy on when to free objects.  Basically, you free any object you create.  You“create”an object using a method whose name begins with “alloc” or “new” or contains “copy”.  If you own an object, you are responsible for calling “release” on the object.  Do NOT call release on an object you do not own or you will most likely cause very bad things to happen because the object will have been freed before it was supposed to.  If you just follow this convention in your own code, you should reduce your chance for this kind of bug.

There are some classes that have convienience methods that return new objects but are not considered created by the calling method.  They are not named with “alloc”, “new”, or “copy”.  One example is [NSString stringWithFormat].  This returns a newly created string, but it is created as an autoreleased object.  Since we don’t control when they are released, it’s good practice to avoid using them unless there’s a good reason.

I know this is going to trip me up since I’ve been using garbage collection in java and C# for for a LONG time.

Class Methods and Instance Methods

- (id) foo {
    return foo;
}
+ (id) foo {
    return foo;
}

The first thing this c# developer noticed was that little “-” minus sign at the start of the line.  In the java and c# worlds, we are used to putting private/protected/public in front of these methods.  I assumed that this was probably a private designator.  Wrong.  This minus sign actually identifies this method as a method that can be used on an instance object.  In both java and C#, you do not put anything in front of the method to identify it as an instance method.  The “+” plus sign designates a class method.  This is similar to “static” in java and C#.  When I thought about it a little more, it makes sense.  In Objective-C you have an interface file where you declare the public methods.

Object Identifiers

The second thing is (id).  id is a built in type in Objective-C.  It is the object identifier.  It is a pointer to a struct. All objects are of type id.  In a similar way every object in C# inherit from “Object”.

[Updated: 6/11]

id is more similar to the “var” keyword in C#.  It’s simply a way of using dynamic typing instead of static typing.  Thanks Martin.

Properties

You declare your property i the import file as follows:

@property (retain, nonatomic) UILabel* foo;

The retain here is required because the iPhone is not garbage collected.  It will give you a warning if you do not put it here.  The other attribute nonatomic tells the compiler that it doesn’t need to worry about creating thread safe code for the methods.

There are two different ways to implement the property.  We will discuss the verbose way first.  When creating a property called “foo”, you need to create two instance methods “foo” and “setFoo”.  This is more similar to the java way of handling properties except in java it is “getFoo”.

- (UILabel*) foo {
    return foo;
}
- (void) setFoo: (UILabel*) aFoo {
    if (aFoo != foo) {
        [aFoo retain];
        [foo release];
        foo = aFoo;
    }
}

The other way to implement the property is a shortcut where the compiler implements it for you.  It would only work for simple getters and setters but it saves typing when they are boring methods anyway. You simply add the following to the top of your implementation file:

@synthesize foo;

MVC

It seems to me that the MVC architecture is used by default when writing an app for the iPhone.  You can write MVC in any platform, but what I’ve noticed is that most developers tend to program based on the first examples they read. One aspect that I haven’t quite figured out is the whole Interface Builder and the whole IBOutlet stuff.  IBOutlet is basically just a define, but Interface Builder uses these tags to know what is available to connect things.  You can drag connections and events using these tags.  I don’t think I fully understand what I’m doing when I’m making the connections.  I understand how to make things work, but I guess I don’t understand on an intuitive level yet.  Hopefully more experience will give that to me.

Playing a sound

Whenever this button was pressed, I wanted to play a sound.  Here is the code I used to do this:

SystemSoundID soundId;
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *path = [mainBundle pathForResource:@"filename" ofType:@"wav"];
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundId); 
AudioServicesPlaySystemSound(soundId);

I have these in different classes but this is the correct sequence.  I created a SoundEffect class do do the actual audio work so I don’t have a reference to the audio includes in the main part of my program.  This should work, but if not, I followed this good tutorial: http://www.iphonedevcentral.org/tutorials.php?page=ViewTutorial&id=50&uid=57348970.  You will need to include the AudioToolbox in your Frameworks in order for this to work.

 
0

rekindled

Posted by jason on Jun 9, 2009 in Uncategorized

I am going to write about rekindling my passion for programming.  Working for go nowhere corporate giants for the past eight years really sucked the life out of me.  It left me with a fat wallet but no passion.  When I worked for startups, I had a passion for writing code.  I miss the days when I’d work until I was so exhausted I would take a nap under my desk at 4am.  I hope to take a sabbatical over the next six months to reignite my passion.  My wallet will get thinner but my passion for coding will be renewed.  I have Startup Weekend Boulder 2009 partially to thank for this.  It was during this weekend where I rediscovered what it is that I am passionate about.  I’ve always been happiest in my career when I’ve learned new technology.  I am going to learn lots of new technology.

I wrote my first program as an 8 year old in 1980 after my dad gave me my first computer.  It was the Commodore Vic 20.  The 20 stood for 20kilobytes of RAM.  My new MacBook Pro has 2,000,000 times more RAM.  I saved my first program to a cassette tape.  I felt so powerful with my little 10 line basic program.  It wasn’t until 1990 that I truly fell in love with programming using Turbo Pascal 5.5.   I loved it because it was Object Oriented and I just “got it”.  In 1995 I became obsessed with the thought that I could put web pages on the school network and anybody in the world could see them.  In 1996, I learned Perl so I could write my first CGI programs.  I did this while I was supposed to be learning scheme I think.  In 1999, I fell in love with Java because it made programming for the Internet easy and object oriented.  In 2003 I learned C# because it was like java but you could write Windows apps.  In every single one of these situations, I learned the language just for the love of coding.

I met some passionate coders at the Startup Weekend in Boulder.  I went hoping to meet people who love technology and I was not disappointed.  There were lots of folks with passion.  Corey Donohoe especially reminded me of the passion I used to have.  Since I’m most passionate when I’m learning new things, I’ve decided to learn a new (to me) operating system, new (to me) programming languages, and I’ll even use technologies I previously thought were kinda dumb (twitter, facebook, etc).  During the weekend we were also encouraged to start a blog by Startup Weekend founder, Andrew Hyde .  I’ve toyed with the idea a while, but didn’t really think I had anything worth while to contribute.  Even if what I write has been written somewhere else, at the very least, I will be another entry that will show up in google when other people have problems with code.  Maybe a different perspective on the same solution will help others out.

This will basically chronical my experience as primarily a Windows/Java/C# developer learning all things Mac/Ruby/iPhone.  I’m learning how to use a Mac because they are just so darn pretty.  Well, the real reason is because I want to do mobile development.  Mobile development reminds me of 1995 when I first discovered the web.  And the king of all mobile devices is the iPhone.  Also, I can do blackberry and gphone apps on my Mac using Java.  I can even do windows mobile if I install Windows in a virtual machine on my Mac.  So logically it just makes sense to own a Mac.  Plus, I think the OS is a work of art and it’s past time I learn it.  I want to learn Ruby primarily because the folks I noticed that were most passionate were Ruby coders.  The Ruby website excites me when I read things like: “Its fans call it a beautiful, artful language.”   The Ruby on Rails website excites me with these statements: “optimized for developer happiness” and “lets you write beautiful code”.  I can’t wait to get started.

Copyright © 2010 programming with passion All rights reserved. Theme by Laptop Geek.