Some Nice Features of the Objective-C Language
March 13, 2008 by Philippe Mougin
Here is a little list of things that, in my experience, contribute to make Objective-C a powerful and fun programming language.
Classes are objects
Each class is an instance of a meta-class automatically created and managed by the run-time. We can define class methods, pass classes as arguments, put them in collections and so on. To create an object, we just send a message to the class we want to instantiate. No need to reinvent a "factory" system. No need for a specific constructor mechanism at the language level. This helps keeping the language simple and powerful.
And, by the way, meta-classes are objects too!
Dynamic typing
As in Ruby, Python, Smalltalk, Groovy… Extremely useful because we don’t always know beforehand what our objects are going to be at run-time. Dynamic typing in Objective-C is simple to use. For example, this declares a variable that can hold a reference to an object:
id myObject;
Optional static typing
Still, Objective-C also has support for static typing. Best of both worlds.
This declares a variable that can hold a reference to an object of class (or subclass of) NSView:
NSView *myObject;
Categories
Categories let us define new methods and add them to classes for which we don’t have the source code (such as the standard Cocoa classes provided by Apple). This makes it easy to extend classes without resorting to subclassing. Extremely useful to adapt existing classes to the requirements of frameworks we want to use or create.
Message sending
We interact with objects by sending them messages. Often, the receiver of a message will have a method that directly matches the message (i.e. that has the same name, or, in Objective-C terms, the same selector). In this case the method will be invoked. But this is not the only possible outcome, as an object can choose to handle a message in other ways such as forwarding it to another object, broadcasting it to a number of objects, introspecting it and applying custom logic, etc.
Very powerful…
Expressive message syntax
Message patterns in Objective-C are like natural language sentences with holes in them (prefixed with colons). When we write code that sends a message to an object, we fill the holes with actual values, creating a meaningful sentence. This way of denoting messages comes from Smalltalk and makes the code very expressive.
Example, sending a message to an ordered collection, asking it to insert a given object at index 10:
[myCollection insert:myObject atIndex:10]
A message sending expressions can be read like a sentence where the receiver is the subject and the message is the rest of the sentence (for instance, an action that we would like the receiver to perform): "myCollection insert myObject at index 10".
Introspection
Introspecting objects is easy. For example, we can ask an object for its class like this:
[myObject class]
Determine if an object has a method "foo":
[myObject respondsToSelector:@selector(foo)]
Ask an object for the signature of its method "foo":
[myObject methodSignatureForSelector:@selector(foo)]
Ask a class whether it is a subclass of another class:
[class1 isSubclassOfClass:class2]
And so on…
Dynamic run-time
Objective-C has a dynamic run-time. It allows crafting messages at run-time, dynamically creating classes, dynamically adding methods to existing classes, changing method implementations and so on…
For a nice example of what can be achieved with Objective-C introspection and dynamism you can have a look at this article I wrote about the graphical object browser provided by F-Script.
Automatic garbage collection
The automatic garbage collector runs in its own thread, concurrently with the application code. It uses a generational model to improve its efficiency by targeting in priority memory zones that are more likely to be garbage. It works for objects and also for raw C memory blocks allocated with the NSAllocateCollactable() and similar functions. malloc() works as usual, providing control over memory not managed by the collector.
The garbage collector is an opt-in service: you can choose to not make use of it in your application and instead rely on a reference counting system. This system includes a rather ingenious delayed release mechanism that goes a long way to reduce the burden of manual reference counting.
Note that at the time of this writing, the automatic garbage collector is not available on the iPhone.
C inside
Objective-C is primarily an object-oriented extension to the C language and constitutes a superset of C. This means that the raw power of C is available, and that C libraries can be accessed directly (as you know, there is quite a number of them available out there!). Beside, this creates a symbiotic relationship between the language and the operating system, as Mac OS X, which is a UNIX system, is primarily written in C and, for the upper-level parts, in Objective-C.
C++ fluent
Not only is Objective-C a superset of C but it can also understand and call C++ code. Used in this configuration, the language is named Objective-C++ and allows mixing Objective-C and C++ code in the same code statements. It also allows directly using C++ libraries.
Simplicity
Objective-C’s Smalltalk-inspired object system is leaning toward simplicity. Many features that tend to render languages complex (templates, overloading, multiple inheritance, etc.) are simply absent from Objective-C, which offer simpler programming models taking advantage of its dynamic nature.
Access to Apple technologies
Each new version of Mac OS X, and now, of the iPhone OS, is full of interesting new technologies which are directly available from Objective-C to play with. This contributes significantly to make Objective-C fun to use.
isSubclassOfClass: is YES if the receiver is *a subclass*. To emulate Java’s instanceof, use isKindOfClass: instead.
I replied to this. Essentially, I can’t agree that Categories are nice - the ability to decorate existing classes is nice, but categories are not a nice solution.
I am a C# developer during the day but am learning Objective-C at night, and what I noticed was that while C# has the “object” that is analogous to the “id”, it works a little differently in Objective-C…
In C#, in order to use an object as a more specific type, you have to cast it to that type, then you will gain access to the specific properties and methods that the specific type offers.
In Objective-C, you don’t have to do that at all… you pass in an NSArray * into a method that accepts an “id” and when you get the code sense on the “id”, you see all of NSArray’s available methods.
It’s pretty cool, and makes things a bit easier that doing all that “someObject is someClass” and then casting stuff in order to gain access to the specific type’s information…
Just my .02 :-)
I agree, ObjC has some nice features. But, for the most part, I find it extremely frustrating from a Basic/C/C++/Java/C# background.
First, the whole use the “id” thing can be nice, but it can also be the devil :) I don’t know how many times compiler will issue no warnings but compile code just fine but I’ll get a runtime exception of object does not respond to selector. I like a little static type checking to make sure the right object is ensured to be given to a method. For small scripting tasks, dynamics typing is fine… but, for larger projects, and application development, it is really good to not have to worry about that amongst everything else that needs to be worried about.
In regards to GC, I believe this is a new ObjC 2.0 kind of feature and is not compatible with any old ObjC libraries. And, the manual release, retain, autorelease, et al is simply a pita and prone to error and memory leaks (not too mention that you have to create and manage your own autorelease pools per thread). I’d rather just malloc/free myself.
But, as I’ve spent more time with the language, those issues have become less problematic, but it definitely is not a easy to pick up language.
Some smaller nitpicks:
* Typing [something something:somthing somethingelse:somethingelse blah:blah moreblah:moreblah] is pretty annoying. If you can’t read the names of the parameters from the method declaration (or autocomplete), you shouldn’t be programming. Double typing things just makes my fingers hurt ;)
* Not very cross platform… Only good reason to use ObjC is to develop for Apple products, and only when making GUI apps that need access to Cocoa (since Carbon is more & more phased out).
Probably some other things I’ve forgotten. Anyway, don’t get me wrong, I like it better than C, C + MFC or C + Win32 API (for GUI, Cocoa is not too bad)… but guess I’ve been a little spoiled using things like Java and .Net (and C++).
Expressive message syntax: I dont agree with this, i totally disagree, because of the sintax:
[myCollection insert:myObject atIndex:10]
i think is better
myCollection.insert(myObject,10)
atIndex is just a param name, you can call it like you want, yes objetive c have a very well writter coding paper, but you can have the same in all lenguajes
@Chocolim
atIndex isn’t a param name, it is actually part of the method name.
The method signature is probably something like that:
- (void) insert: (id) object atIndex: (NSUInteger) index;
where the parameters names are “object” and “index”.
So, the method name is:
insert:atIndex:
not “insert” with two parameters.
@Chocolim: myTable.insert(myObject, 10, YES);
Can you tell me what that YES stands for?
In ObjC you always know:
[myTable inert:myObject atIndex:10 animate:YES];
simple, easy and you don’t have to type everything — Xcode gives you hints ;)
[...] Some nice Objective-C features Categories let us define new methods and add them to classes for which we don’t have the source code (such as the standard Cocoa classes provided by Apple). This makes it easy to extend classes without resorting to subclassing. [...]
Coming from a Delphi, Visual Basic and now C# background, I find Objective-C to be frustrating.
I started programming Windows with C and then C++ and I hated it. To many cryptic lines of code. It took a lot of work just to be able to read code samples. Even with that background, I am finding that learning Objective-C involves a pretty steep learning curve.
On the other hand, I believe that my frustration is psychological. I am used to what I am used to. Programmers get comfortable with what they know and when something pops up that’s a bit different from what they know, then the initial reaction is that it sucks.
When I first saw how methods are declared, I asked “Why can’t they just use the syntax I’m used to?”. But now I realize that named parameters (that’s what I call them right now) are pretty nice.
The bottom line is that it’s just going to take some time to get used to the differences. I keep saying to myself “Everything in life is a tradeoff. If you want to write software for the iPhone, you’ll just have to suck it up and do it instead of complaining.”
Objective C is very powerful and flexible. My only real beef with it is that, as most often with language, with power comes responsiblity. It is easier to debug a more heavily typed language; I find debugging Objective C much tougher than C++. There is also the fact that C++ is a language I can take to other platforms, whereas Objective C is pretty much mac only.
As much as I like it, if I could have a C++ interface to the NS framework I would take it over Objective C just because of familiarity. Still, the desire to code for the Macintosh has me learning it…
I have been working with Objective-C for a long while now. Made a game engine, a few games, etc. I’m pretty sure I still have a lot to learn about it, so I won’t come out as an expert, but I’m used to it by now.
And I definitelly prefere C++.
Here’s my reasons, which can be valid or not depending of your needs/habits.
1) No smart pointers. This is the biggest killer for me. Under C++ I’m addicted to weak pointers, scoped pointers, shared pointers, etc. They are so elegant and simple to use, yet making the code so much solid and safer, that I really have a hard time in Obj C to deal with pure, naked pointers without grinching my teeth.
2) No templates. Yes I know, templates are a pretty good weapon to make a code unreadable. But used in small and intelligent doses, it IS a real benefit. Like driving a car, don’t do it if you don’t know how to drive wisely. But don’t force ME out of it.
3) I still prefere the good old method() calling convention. I understand the example about the “YES” parameter given above. But with the powerful IDEs we have today, moving the mouse over the function is all it needs when something is confusing. To me long ObjC listings are just harder to read than C++.
Oh and I forgot about strong/loose typing. That’s two schools with their pros and cons, but I’m definitely a fan of the strong typing.
My favourite thing about Objective-C: I love messaging nil. In Objective-C sending a pointless message to nil returns nil.
None of Smalltalk’s “Message not found: ‘nil DoesNotUnderstand: #selector”‘
None of Java’s “java.lang.nullpointerexception()”
None of C’s “segfault”
Just sweet beautiful nil, it avoid cluttering your programs with “(anObject isNil) ifFalse:[anObject doSomething].” or try… catch blocks, or checking if an object is null before sending it a message or whatever else you have to do.
In regards to nil, it is nice not having to always check for nil and simply getting a nil back from functions.
However, you still have to worry about pointers, because a double release, or calling a selector on an already released object can cause some hard to find segfaults :D (Not much different than C/C++), but trying to always match up retain/release can sometimes be a pain.
The funny thing is when C++/Java/C# folks come in contact with ObjC many of their responses are like Steven’s- a lot easier, intuitive, and productive. Why is it funny? Because ObjC itself is just a shadow of its progenitor- Smalltalk. Many of the objections people put forth for ObjC disappear- it’s a ton easier to debug, for one.
Just a thought.
NCIceman: If you consider C++ portable, then ObjC is just as portable. ObjC++ too, though there maybe some fuzzy specifics on that one. When it comes down to it, it’s the platform and API, not that language that really inhibit portability. Yes, if you write an ObjC app for Cocoa, you won’t be able to compile it (easily; there are ways!) on Windows as-is. But neither would you be able to compile and run a C++/Win32 app on OS X, not without a similar amount of pain, and it’s possible that amount of pain would be the same on Linux.
In the end, both C++ and ObjC aren’t meant to be portable, and any porting project will be a PITA. It’s easier to get and use Foundation.framework when bringing ObjC code to a Windows box than to try to figure out wine+C++ on a Mac. :)
I dunno, not all apps are GUI apps. I find it much easier to write portable code in C/C++ that compiles under Solaris/Linux/Windows/OSX than I do to write ObjC code and find a good compiler/runtime on anything other than OSX. I’m not sure where you contemplate trying to bring Wine to Mac? Win32 API is not C++. C++ is very portable, and is very standard, and is used in very many commercial applications out there. All that is required is simply using a little abstractions or ifdef’s and a windowing GUI API can be easily compiled in/out.
I don’t get your point about ObjC being a ton easier to debug than other languages? Or are you referring to Smalltalk? Because, by far, the best debugger I have ever used in on Windows (MS’S VC Debugger) and can easily debug assembly, C/C++, Managed, Web Apps, etc all exceptionally.
In regards to cross platform GUI apps, for C++ is is very easy to write easily cross platform Apps using wxWidgets, or other tool kits. Alternatively, I would use something like Java if I really wanted cross platform GUI (might even make use of Eclipse or Netbeans platform).
The point really, is I am not against ObjC. It is a perfectly valid language as languages go. However, I feel C++ has surpassed it, and Java/.Net platform are far easier to develop for. However, for me at least, the *only* place to use OjbC is on Mac and/or other Apple products… Which, kind of makes using it for applications you want to work on other operating systems too pretty lame.
I read a lot about objc in the past few days since I read this article. One thing i’m missing here. Is Objc2.0 free for use.
Does it have a compiler for Linux? And what about the base class library? Is it open source? what license?
Does apple hold any patents on the language? will they sue if used on other platforms?
looking in my Ubuntu apt repositories it seems like there’s only support for version 1.0 of the language in the form of gcc, which mean that many cool reatures you mentioned wouldn’t work, like attributes for instance.
[...] Per approfondire Objective C (in particolare l’ultima versione 2.0 dotata di funzionalità interessanti nonchè di un Garbage Collector) potete consultare: Introduction to The Objective-C 2.0 Programming [...]