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 ;)
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++.
On your last point I have to disagree. I can look at my objective c code in a text editor without needing to chase documentation. Methods in objc are clearly defined and easy to use. I don’t have to litter my code with comments and generate docs like java or c#.
Lots of people like c++ but most I kow avoid it if necessary. As far as IDEs and frameworks Xcode and cocoa do everything needed and can use any c or c++ goodies whenever.
Some people swear by eclipse and vs. I never much liked them till very recently. C# is cool too but are not in same league as objc by definition.
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.
All of you who said ObjC is bad, or lame, well… I guess I could expect that you probably like VB too.
Chris, the Delphi programmer, is especially obtuse to me since, for the most part, Delphi *works* exactly as does Objective-C. To clarify, because I know he’s gonna say ‘no it doesn’t’, there may be syntactic differences between ObjC and Delphi, under the hood the work exactly the same way: Look at the mechanics of Delphi and you’ll understand what I mean.
PjCast, you probably couldn’t malloc to save your butt. Besides, when one is dealing with code whose performance is critical one must have some way of verifying that performance. You can’t do that with mallocs sprinkled everywhere and expect meaningful results. Also, before .Net there was COM and it used reference counting and it *truly* sucked in its implementation/concepts which is why MS replaced it with a design of the same guy who designed *Delphi*. (BTW Chris, Delphi took a significant amount of its design from MacPascal). Keep PInvoking to your hearts content PJ.
My point is that if you are going to comment on a language, please do some work to understand what you are speaking of before opening your mouth. If you simply want to bash something, go bash your head into a wall. If you want to whine about something, go whine to your mothers; They probably care.
In the end, it is a fact that there have been exceedingly powerful solutions that are ignored in favor of the one that attracts the most idiots. Such has been the case with Objective-C. As a strict superset of C, you can take it or leave it, without having to sacrifice anything. Try doing that with C++.
@Dave
Yeah, I couldn’t malloc to save my butt… if that’s the best rebuttal you have your pretty lame. I’ve work with many many languages/scripts/etc (basic, c/c++, java, C#, python, objc, squirrel, lua, psql/tsql, etc) and many platforms (dos, windows, mac, linux, unix, iphone, embedded, etc ) and by far, the slowest development platform is ObjC. Because, 1) the language is not intuitive, 2) the main IDE (Xcode) is subpar for debugging & developing, 3) errors happens mainly at runtime.
Not sure what your argument is about COM. Sure, COM was before .net, and a lot of .net and windows still deal with COM. I don’t think COM is nice, but it is still used for many of Windows components. And wtf about pinvoking? Not sure where that ties in at all in this conversation. Pinvoke is useful, just like Java’s JNI is useful – or any other C linkage interop.
Great list. Not used all of them but it’s nice to know they’re there!
My list would include the use of delegates, which I guess is more a function of Cocoa than Object C per se, but it’s certainly something that I feel makes me very productive.
Other languages I’ve used tend to force you to subclass everything, which seems to result in dozens of tiny files with a small number of methods, which makes it much more complicated to edit and debug.
coming from a C++ , pascal, vb, perl and unix background, it’s clear for me objective C is superior.
its syntax is clear, the runtime is reaaaally powerful, the naming convention of functions are so nice to read and to understand code (and yeah, there are modern IDE, it’s a tremendous feature of the language itself)
it’s conceptually a C superset. it matters. a lot.
It has real object types or not. I have the option. It has introspection, real object-type class, now a opt-in garbage collector. best of both world.
it’s not a different langage. it’s C. There are no horrors as in C++ (templates! ), you can link to whatever C libraries.
and beside, Cocoa is a nice frameworks build upon and thanks to objective C. Delegates for exemple is an impressive tool.
–
all of that is a clean implementation.
–
and ho yeah ! F-SCRIPT !
I like Objective C’s approach, a totally novel way for me, used as it is to C#, VB,VBA and C. Though I have never developed a full fledged Win32 application, I jumped right into Cocoa Touch. The whole XCode/Obj C combination is a whole lot of newness to swallow…but the more I read about Objective C the more XCode makes sense too. It’s really frustrating to not be able to start churning useful code out right away, as I can usually do in C#…definitely a learning curve. But that does not mean we should be putting down the language. Studying Obj C has taught me a lot more about OOP than anything I have done so far.
I’m frequently amazed (but seldom surprised) at the dogmatic responses that inevitably crop up when discussing programming languages. Frequently, and particularly for Objective-C, the comments are pretty baseless when it really comes down to it. Let’s have some fun with this one….
“But I can’t use it to write cross-platform code.”
No, Objective-C won’t compile on your Commodore 64, but that’s really not the point. C# doesn’t (easily) run on Linux, but that doesn’t mean it’s not useful. If you’re using Objective-C or C#, that probably means you’re writing code specifically for OS X or Windows, respectively. THIS IS NOT INHERENTLY EVIL. Different problems often call for different solutions. If you’re writing a cross-platform program, by all means, use the tool that offers the lowest common denominator. But if you want to write a really nice, polished program, realize that the better way is usually to use the tools specific to a given platform. When all you have is a hammer … try to remember that other people use screws, or rivets, or glue, or something else in place of a nail. And that’s okay.
Honestly, while the language features are really cool, probably the biggest win with Objective-C is the Cocoa frameworks written by Apple. In addition to a whole slew of low-level and back end functionality (like data structures, network connection, threading, I/O, archiving (a.k.a. serialization), interprocess communication, etc.), Cocoa includes a flexible and mature set of GUI widgetry with proper MVC abstraction. (Consider: what would be the allure of Java without the standard Java APIs, or of C++ without all the default libraries or the STL.) Those of us who love Objective-C choose to sacrifice cross-platform compatibility in order to regain development time which would otherwise be spent writing glue code and manually doing a lot of what Cocoa does automatically. Out goal is not to write one program that runs everywhere; it is to write an application that is polished and runs well on one platform, and to not spend more time that we’d like on writing it.
“Dynamic typing is teh roxxor/suxxor!!1!”
Good, that’s why Objective-C gives you a choice. If you get frustrated by runtime errors that occur with dynamic typing, there’s an easy solution: use that *optional* dynamic typing mentioned in the article. It’s allowed, and even encouraged. Most of the time, I prefer static typing since the compiler can provide more intelligent and helpful warnings than when using the “id” type. However, there are many situations where I really don’t want to cast objects all over the place just to let me call a method I know it has; that’s a great time to use dynamic typing. Also, people who haven’t a clue about the Cocoa frameworks (or F-Script for that matter!) don’t realize that dynamic typing makes possible a whole bunch of really cool things you can’t easily do in strict statically-typed languages.
“Yeah, ___ is cool, but it can also really get you into trouble.”
This is similar to arguing that “Well, English is very expressive and cool and everything, but there are some words that, if you say them at the wrong time or in the wrong place, can get you shot. Therefore, English must be a horrible language, and we should all go back to speaking Latin (or whatever), since it’s safe.” The whole point is that certain features exist for very specific applications, and nobody is twisting your arm to use them all the time, or ever. (Dynamic typing is a great example of this.) As a computer scientist, I would submit that people who write languages tend to think about language features a lot more than people who use languages. (They’re often smarter than you, too.) If you think a language/feature is the stupidest thing ever, you’re likely not the target audience; it was written for someone else, and they absolutely love the language/feature, because they use it all the time and it makes their life easier.
“Memory management is Objective-C is terrible/confusing/annoying.”
With all due respect, it’s probably because you don’t understand it fully. The retain-release model is mature and powerful, but it’s not simple, so there’s definitely a learning curve. However, reference counting generally makes it easier to understand and explicitly implement memory ownership, such that no one chunk of code has to be the one to explicitly free() the memory. This tends to open up tons of possibilities for dynamic behavior, but it does require that each piece of code that deals with allocated memory follow the rules. If you play by the rules, things just work.
Looking toward the future: yes, garbage collection is new in Objective-C 2.0 (in Leopard), and yes, it does introduce some incompatibilities with older compiled code. (If you can add a new feature to language without that side effect, please let me know.) As legacy code is updated, people will increasingly benefit from optimizations in GC technology, but it doesn’t all happen at once. And honestly, the process of supporting GC is usually pretty straightforward, and the most important libraries (the public Cocoa frameworks) already support it. Third-party GC support will increase over time. (By the way, Obj-C 2.0 supports weak pointers with the __weak keyword … check it out.)
“The method names are really long and hard to read/type.”
Two questions: (1) Have you actually worked on Objective-C code, especially if someone else wrote it? (2) Seriously, what IDE are you using, and if it’s not Xcode, why not? A good portion of the arguments that defend C/Java-style method calls is that “you can just hover over the call to see the parameters”. Hmm, sounds like an IDE feature to me, not something you’ll see in vi/emacs/Notepad, let alone if you’re looking at a code listing on a webpage or in a book. When you read Objective-C code you’re not familiar with, it’s pretty easy to figure out what it’s doing, especially if it (and any third-party libraries) are reasonably well-designed. I great example is Java constructors versus Obj-C -init… methods. Yes, it takes some getting used to, but it makes for code that more self-evident. Xcode and Objective-C play together quite nicely, including code completion and other features that make working with long Obj-C methods names a snap, and you can bet that the dev tools are only getting better in Snow Leopard.
“Why can’t I have two methods with the same name in one class?!”
This can occasionally be a sticking point, but it does allow for really smart optimizations in the dynamic runtime (such as for introspection) and tends to force you to think about what your method name should actually be, and what it accomplishes. The outcome is generally cleaner code, and the expense of more up-front thinking. (Please, don’t try to convince me that’s a bad thing. I’ve worked on too much crappy, ambiguous Java/C++ code to agree with you.)
“Objective-C only makes sense for building GUI applications.”
Not necessarily true, but that is what it excels at. Interface Builder is a phenomenal tool — don’t knock it till you’ve tried it. Creating GUIs with Cocoa pretty much blows away anything in Java, C#, GTK+, wxWidgets, or anything else. And if you’re still brushing aside GUI apps as a fad or annoyance … unless you’re writing system-level software (e.g. drivers), let’s just say that you’re probably limiting your potential user base.
Quinn Taylor said everything, excepted that Objective C *is* portable on Windows and Linux thanks to GNUstep (yeah, GUIs are very ugly with GNUstep, so use Chamaelon framework in addition to it).
I’m used to languages where this is all you need to do to get text from the user:
> answer = prompt(“Enter your name”);
Do you know how much reading, studying, writing, and debugging I had to do… just to do that in Objective-C????
And, when done, I’m still not sure it’s ‘right’.
And it’s 15 lines of confusing code.
@Debbie, if you know how to get a prompt from the user in strict C then you’re all set. No need to use Objects for a “get input and print it out” program.
What if I had to write a generic routine that accepts no parameters, and returns nothing. (It just does all it needs to do… within itself.)
I tried to create a c-function… but I couldn’t seem to call it from within my Objective-C methods.
Is there some secret to getting this to work?
[…] fairly new to objc (which btw is cool) and iPhone dev, studying real world apps _really_ help a […]
OcjC is probably the only C-ish language I would choose to use anymore. I’ll take Smalltalk style OO (message passing + syntax) over anything else hands down.
NextStep was one incredible system and the fact that the libraries are in such wide use due to apple is great. Unfortunately there are no major Smalltalk systems being sold :)
As far as cross platform goes (for any large project) you want to write the view code for each platform specifically anyway. But since ObjC is a strict superset of C (or C++) it makes it easy to use GTK/QT/Win32/Cocoa for each and be fine. You can even use GnuStep to get some foundation classes going for windows/linux (not gui code). I find myself not liking apps that settle for WxWidgets and other cross-platform libraries anyway cause they never feel right.
From a language standpoint I’ve never been a fan of java. The VM is awesome, but I can’t stand using the language, so most arguments about Java > sometime else just go out the window for me.
Dynamic typing
You say “Extremely useful because we don’t always know beforehand what our objects are going to be at run-time.” Why don’t you know, what your objects are at runtime? I claim that in order to do something with those objects of arbitrary type you need to know something of them. For example: You have a sort function and you want to sort objects of some kind. Then you know, that there has to be some comparison method defined on the kind. And at compiletime you already know what kind of objects you are going to sort. the compiler could inferr it. if you know nothing of the objects (besides that they are objects and the methods of NSObject are defined) then you could not do much usefull things with them. (well you could store them in an array and retrieve them. but if you have retrieved them, what are you going to do with them, since you don’t know any method that is defined on them.
So please clarify what you mean by “Extremely useful”. I can’t follow your argument. Maybe you mean that it is nice, that you don’t have to say/write that you implement the compareable interface, but you just provide the method and by doing that you implicitly have the interface. But hey, you only save writing in the @interface line.
As I said, I don’t really understand your argument. Thanks for your feedback. I always like to learn.
Nikolas,
Your comment about the need to know something about an object to interact with it is spot on. But all you need is to have this knowledge at run-time. Not having it at compile time does not prevent you to do something with an object if you can acquire at run-time this needed knowledge. And this is why dynamic typing is so powerful. This is particularly important with open systems, where the set of possible object classes or interfaces is not fixed (e.g., new classes are dynamically loaded at runtime or dynamically generated – things dynamic systems, including Cocoa, do routinely). This is also very useful for creating modular, loosely coupled and flexible subsystems. Look for example at how Cocoa implements its target/action paradigm: the target object can be any object (no knowledge at compile time) and the action (i.e., here, the needed knowledge about this object) is provided at run-time.
imo C# 4 is the superior language syntax-wise with LINQ, lambda expressions, parallel and reactive extensions. The only problem with it is you have to use .NET’s heavy weight WPF for UI which has tonnes of functionality while missing basic ones (no MVVM implementation).
I recently began obj-c and am quite negative about its syntax. It’s very different and mostly requires boringly much typing for simple stuff. dot notation is far more readable than [ ] notation. spliting method names isn’t UML friendly.
I wish we could use c# with xcode and the language had support for OMG’s OCL like stuff for querying through hierarchies of objects and handled exceptions as JAVA did. That would be the perfect mixture of technologies.
[…] Some Nice Features of the Objective-C Language […]