Kuro5hin.org: technology and culture, from the trenches
create account | help/FAQ | contact | links | search | IRC | site news
[ Everything | Diaries | Technology | Science | Culture | Politics | Media | News | Internet | Op-Ed | Fiction | Meta | MLP ]
We need your support: buy an ad | premium membership

Introduction to Cocoa with Objective-C

By liquidcrystal3 in Technology
Mon Apr 05, 2004 at 05:21:55 AM EST
Tags: Software (all tags)

No, I'm not proud of using a proprietary operating system, but Apple's Cocoa + Development Tools is just about the richest, simplest and most powerful programming environment anywhere. If you are interested in Cocoa and don't have a Mac there is an open source, cross platform (but not nearly so complete) implementation available called GNUstep.

Here is an introduction to the style of Objective-C Cocoa and some reasons why I hope more programming will be done in this style in the future.

Cocoa and GNUstep are both the offspring of OpenStep, which is in turn the offspring of NeXTStep which is the software platform NeXT Computer Inc. decided to develop for their hardware in the 80's. Of the two, Cocoa is the most complete in terms of frameworks, documentation and development software and I write about Cocoa here because I am more familiar with it and because it is closer to what GNUstep should (will) be than GNUstep is, though a lot of this will apply anyway.

Both Cocoa and GNUstep are object oriented programming environments comprising of an integrated editor/compiler/interface builder and a set of frameworks (dynamically linked libraries) which store almost all of the typical objects (and their methods) you might want in an application. As well as Objective-C, Cocoa programs can also be written in Java, even AppleScript, perl or python and there is no reason why more languages should not be added.

Objective-C is a thin layer on top of C in the mold of Smalltalk, the only syntactic change to C is the addition of messages in the form

[object method]
which sends the message "method" to "object" or if you prefer, means object->method(). Arguments are separated by colons ":" so
[object method:argument1 :argument2]
tells the object; "method with argument1 and argument2" or means object->method(argument1, argument2). Objective-C is dynamically typed (unlike staticly typed C++ and Java), which means you can send messages to objects that don't know how to receive them, in Cocoa that means that the message gets passed along the receiver chain until it meets an object that does, which is handy if you don't know exactly where it will be used when you write the code. Dynamic typing and genuine message forwarding also mean that objects can be distributed across applications and even across networks and still be accessed with the same simple [object method]. Dynamic loading means that Obj-C programs can even load plugins and code on the fly at runtime.

The basis of Object Oriented Programming is of course 'objects' and you may recall that reusability and inheritance are among the benefits OOP offers, in Objective-C objects generally inherit or are descended from a root object and in Cocoa the root object is called NSObject (a name which Cocoa itself inherits from 'NeXTStep'). This simple inheritance means that all Cocoa objects being decendents of NSObject inherit some standard functionality (like conforming to Cocoa's memory management scheme and dealing with message forwarding). Below NSObject in the Cocoa framework there is a tree-like structure of inheritance which contains such things as data containers, GUI elements and application services, each object inherits methods, variables and functionality from its' super and adds to them.

Thanks to Objective-C's flexibility all objects can be classed as being of the type of one one of their ancestors, so both NSButton and NSSlider can be passed as NSControl, useful if you don't know what kind of control you'll be listening for when you write the code. Taking this to the extreme, all objects can be passed as type 'id' - the type of NSObject. This makes sense if you don't know what kind of object you'll be dealing with (perhaps because you are communicating with an application across a network or because you are loading code at run time) because once you have the object or a reference to it you can ask it where it comes from and what methods it responds to and then deal with it accordingly. Sweet.

In Cocoa and GNUstep objects are accessed through a clear and well thought out API which manages to cover just about every circumstance, meaning that applications get a huge amount of functionality for free and making Cocoa/GNUstep a particularly lucid way to program as much of the code is behind the scenes. In Objective-C, a not untypical line of Cocoa code looks like this:

[window close];

Which tells the object "window" to do the method "close". As it happens window is an instance of NSWindow, which means that it responds to the close message automatically without any coding by the applications developer. Of course, that line of code has to be inside a method of an object for it to be called, so in context:

- (IBAction)CancelButtonClicked:(id)sender
[window close];

Yes really, look again:

- (IBAction)OKButtonClicked:(id)sender
float intensity = [intensitySlider floatValue];
[window close];
cpImageData = [self swirlImage:cpImageData size:cpImageSize intensity:intensity];

That's three lines of instructions for the program to go through when the user clicks the OK button. Of the three methods used, (floatValue, close and swirlImage:size:intensity:) only the last one is not built in to Cocoa and actually needs writing. If you need some functionality that isn't built in already (and you will eventually) you can just subclass whichever object is closest to what you want and add or override whatever functions or variables you want different.

So for instance the class that the above CancelButtonClicked: and OKButtonClicked: are contained in might be a subclass of NSWindowController which would just mean having a header file like:

#import <Cocoa/Cocoa.h>
@interface CPImageFilter: NSWindowController //<---
IBOutlet id intensitySlider;
UInt8 *cpImageData;
NSSize cpImageSize;
- (IBAction)OKButtonClicked:(id)sender;
- (IBAction)CancelButtonClicked:(id)sender;
- (UInt8 *)swirlImage:(UInt8 *)data size:(NSSize)size intensity:(float)intensity;
- (UInt8 *)filterImage:(UInt8 *)data size:(NSSize)size;

and an @implementation file which contains the implementations of the methods like like the one you saw above for OKButtonClicked:. Luckily you don't have to remember the exact structures of these files because the development tools will create outlines for you and Interface Builder will even add the actions and outlets.

Other GUI objects supplied include buttons, sliders, [text/ image /movie /OpenGL /...]Views, toolbars, and menus amongst many others and they can all be implemented and hooked up with your code using drag and drop operations in the integrated Interface Builder application which even draws guides to make sure everything is aligned right. Like Swing, Cocoa programming is event triggered but creating handlers is often code free, just a case of just drawing connections in Interface Builder. Of course if you want dynamic interfaces you can still code or part code them by subclassing the GUI element in question.

Because interface elements are just instantiated descendants of NSObject with some values set (like position, state, color etc) they are not stored in some mangled format but "frozen" as objects by Interface Builder and then dynamically loaded at runtime when needed.

The data structures Cocoa offers include arrays, dictionaries, which store key value pairs, strings, which have a huge variety of methods for creating, comparing, appending, and taking from each other, sets, which can be unioned and intersected and objectified byte data and all of those also come in mutable forms (which can be extended, reduced, and swapped around internally) and all are flexible enough to hold any kind of object. All of them are useful in certain circumstances but tiresome to recode for a single implementation, with Cocoa/GNUstep they're just there waiting to be used, and subclassable if need be.

Application services you get for free or minimal work include document management, undo/redo, printing, scripting, filesystem access and spell checking. If you want to you can import the web kit and build a browser into your application as easily as adding a picture. All of this makes building a fully fledged applications with all the normal functionality you expect very easy.

Memory management in Objective-C Cocoa amounts to making sure you send an [object release] message for every [object retain] you send or alternatively you can send an [object autorelease] message which is essentially a way of telling the application that you are finished with it, the object will be sent to an autorelease pool and when the code reaches the end of it's run cycle, all the objects in the pool will be sent an [object release]. Any object that reaches a retain count of 0 automatically deallocates itself - an example of reference counting garbage collection. Objects are almost universally referred to by their pointers and generally allocated into memory with something like [object alloc] - so no worries about malloc() here.

The clarity of the language, the way you can build applications like Lego in Interface Builder, and the fact that many very powerful features are automated make it the perfect environment for beginners and for people who want to focus on what the program is there for rather than spending a lot of time building an interface or creating some intermediate structure that has been done many times before just a little bit different.

But doesn't throwing these behemoth catch-all objects around carry some overhead? Well, yes it's true that Cocoa apps aren't famed for being like lightning but often speed isn't an issue, when displaying a menu a few extra milliseconds don't matter - especially if you saved minutes or hours coding. When you do need speed (like during gameplay, rendering graphics, complex functions) you can change up a gear. Lower level technologies like Quartz (or CoreGraphics), OpenGL, and QuickTime which aren't as easy to use or as lucid but are faster and more powerful are easily integrated and in Objective-C (a strict superset of C) you can create the usual C arrays and structs, use regular C code and malloc() and free() and &, ^, |, ~, >> and << to your hearts content without any overhead whatsoever.

In the case of our image filtering example this might be implemented by storing the image data in a regular C array (not an object) and making sure that inside of the loops that run through the pixels (where the operations will be called many times) are bitwise C operations and simple functions only. So swirlImage:size:intensity might look something like this:

- (UInt8 *)swirlImage:(UInt8 *)data size:(NSSize)size intensity:(float)intensity
unsigned int x, y, w, h, i;
w = i = round(size.width);
h = round(size.height);
UInt8 *buffer = malloc(sizeof(UInt8) * w * h)
UInt8 *ptr = buffer;
while (h--) //loop through the rows
while (i--) //loop through the columns
x = someSimpleCFunction(i, h, intensity);
y = anotherSimpleCFunction(i, h, intensity);
*ptr++ = *(data + y * w + x);
return buffer;
In short there aren't many programming environments that offer the flexibility, scalability, reusability, ease and power that this one does. Also with high level code which relies only on it's frameworks, there is no reason why one day an application written in Cocoa / GNUstep could not be simply recompiled for another platform from the same code. If you want to update one part of the framework like optimizing some functions or changing the implementation of some service then all of your programs that rely on it will be able to take advantage of the changes with rewriting. If GNUstep becomes more popular and it's frameworks are improved these are real possibilities and when that happens I'll consider a free OS.


Voxel dot net
o Managed Hosting
o VoxCAST Content Delivery
o Raw Infrastructure


Related Links
o GNUstep
o object oriented programming
o perl
o python
o Smalltalk
o Swing
o build
o Also by liquidcrystal3

Display: Sort:
Introduction to Cocoa with Objective-C | 88 comments (69 topical, 19 editorial, 4 hidden)
+1, science/technology (1.00 / 17) (#2)
by Hide The Hamster on Sat Apr 03, 2004 at 11:36:16 AM EST

Free spirits are a liability.

August 8, 2004: "it certainly is" and I had engaged in a homosexual tryst.

More about objective C (2.75 / 8) (#7)
by conthefol on Sat Apr 03, 2004 at 03:35:14 PM EST

It's helpful to note just how powerful the object system is. For example, the 'id' type of object - which can be ANYTHING, and you can send ANY message to it. And it will work. In C++, this would be like if there was a universal class with every method used anywhere else declared as virtual.

But then again, if you just want 'object' to mean 'data with some handy function namespacing stuff' then use C++.

kuro5hin is about to E.X.P.L.O.D.E!!!

Templates, generic programming (none / 0) (#52)
by the on Mon Apr 05, 2004 at 05:46:04 PM EST

'data with some handy function namespacing stuff'
Ah...you must be one of those poor people who think that C++ objects are merely "data with some handy function namespacing stuff". Open your eyes to templates and generic programming. Being able to parameterize your functions with types opens up wide open vistas of programming that are diffcult to traverse using C or the limited subset of C++ of which you speak.

The Definite Article
[ Parent ]
Yeah, I know about that stuff (none / 1) (#56)
by conthefol on Mon Apr 05, 2004 at 08:32:02 PM EST

With what I do, that's what most objects are. A dataset with some easily accessible operations defined for it. I'm not much of a computer sciency type so templates are rarely used.

I mean, sure I could define my numerical codes to use different number types - but who am I fooling? It's going to be double precision every time. :)

kuro5hin is about to E.X.P.L.O.D.E!!!
[ Parent ]

Replacing doubles (none / 0) (#87)
by the on Tue Apr 13, 2004 at 03:56:42 PM EST

I mean, sure I could define my numerical codes to use different number types - but who am I fooling?
I'm currently getting a paper published on exactly that - replacing the double precision type with another datatype in numerical code :-)

The Definite Article
[ Parent ]
Objective C (none / 1) (#67)
by Altus on Tue Apr 06, 2004 at 12:57:31 PM EST

Gives you many of the advantages of generic programming built right in but (In my opinion) it is alot easier to take advantatge of than C++ templates.

the whole thing was designed from the ground up to let you sling around objects without worry, sure you can do similar things in C++ but I find that the it is alot more combersome than it is in Objective C.  

Admitedly I am not a master template craftsman. but I have only used Obj C for a short time and already I am starting to understand and appreciate its elagance.  Ive been coding in C++ for almost my whole career and I still find templates combersome.

Obj C isnt the end all be all of languages, hell, it isnt even new and has many limitations that you probably wouldnt build into a new language but I think that people developng new languages would do well to look closely at Objective C and the style of programming that it allows.

"In America, first you get the sugar, then you get the power, then you get the women..." -H. Simpson
[ Parent ]

In a similar vein (none / 2) (#9)
by speek on Sat Apr 03, 2004 at 04:32:11 PM EST

I could write a one-line OCR engine given Java + javaocr libraries. But, I'm not sure how or why that's interesting.

al queda is kicking themsleves for not knowing about the levees

displaying HTML in a program is useful (none / 2) (#10)
by Haunting Koan on Sat Apr 03, 2004 at 04:44:58 PM EST

Is much more useful than reading text from images for most people. The example is overglorified I agree, but WebKit will proove to be an extremely useful tool for Cocoa programmers a long time to come.

For example, see Colloquy, an IRC client that renders its main view with WebKit.

Similarly, Adium (available now) and Proteus (for version 4.0) are currently working on similar views that render HTML for their chats.

[ Parent ]
Didn't I write this article two years ago? [n/t] (2.83 / 6) (#14)
by epepke on Sat Apr 03, 2004 at 10:44:32 PM EST

The truth may be out there, but lies are inside your head.--Terry Pratchett

Indeed. (none / 3) (#18)
by pwhysall on Sun Apr 04, 2004 at 05:53:14 AM EST

K5 Editors
I'm going to wager that the story keeps getting dumped because it is a steaming pile of badly formatted fool-meme.
[ Parent ]
Looks like... (3.00 / 7) (#33)
by rusty on Sun Apr 04, 2004 at 10:16:33 PM EST

...Cocoa development has really caught fire since then! Here's someone else using it already. ;-)

Not the real rusty
[ Parent ]
I cannot code (1.40 / 5) (#21)
by RaveWar on Sun Apr 04, 2004 at 02:41:24 PM EST

But I do own a mac. It is nice to be told that there is a great programming tool inside, should I discover the ability to code...

Maybe somebody would like to port an oss office programme - any one will do - to run natively on mac.
We don't need freedom. We don't need love.
We want Superpower, Ultraviolence.

AbiWord now available for OS X (none / 1) (#27)
by mcc on Sun Apr 04, 2004 at 04:34:15 PM EST

AbiWord 2.1.1 contains experimental support for Mac OS X and full support is planned for AbiWord 2.2.

[ Parent ]
OpenOffice (none / 0) (#57)
by molo on Mon Apr 05, 2004 at 08:48:09 PM EST

OpenOffice runs natively with the Apple X server:



Whenever you walk by a computer and see someone using pico, be kind. Pause for a second and remind yourself that: "There, but for the grace of God, go I." -- Harley Hahn
[ Parent ]

That is not native (none / 0) (#58)
by Tachys on Mon Apr 05, 2004 at 11:14:07 PM EST

That is like saying MS Office runs natively in Linux with WINE.

Any game that gets banned by the Austrailian govt can't be all bad... - Armaphine
[ Parent ]

not quite that bad (none / 1) (#59)
by Norkakn on Tue Apr 06, 2004 at 12:27:19 AM EST

there isn't any emulation involved, just X11, so it is native, it is just a pain in the arse to use, especially since it is extremely hard to paste into

[ Parent ]
get fink! (none / 0) (#60)
by revkarol on Tue Apr 06, 2004 at 05:42:38 AM EST

If you don't already have it get fink and fink commander (a cool GUI for fink). These will allow you to download loads of decent open source software. For office stuff you should try Abiword and Gnumeric or get KOffice and run this from Apples X11 (or another X11 implementation). Ignore people who tell you to use openoffice. It's a pig in OSX I've found, far too slow (would be a great app otherwise).

[ Parent ]
AppleScript (none / 3) (#61)
by Graymalkin on Tue Apr 06, 2004 at 06:23:35 AM EST

If you'd like to get your feet wet with programming you might want to look into learning a little AppleScript. AppleScript is fairly simple to learn and has an English-like syntax. MacOS X comes standard with an AppleScript editor called Script Editor which lives in your Applications folder. It allows you to write, edit, and record scripts.

AppleScript works by tying into an event messaging system called AppleEvents which goes back to the System 7 days of MacOS. AppleScripts can tap into these messages in order to command other programs to perform actions. Telling Finder to open a folder is pretty simple:

tell application "Finder"
    open folder "Applications"
end tell

This little script when saved as an application (from Script Editor's Save As.. dialog) will open a Quicktime file dropped onto it and play it fullscreen:

on open fileName
    tell application "QuickTime Player"
        open fileName
        present movie 1
    end tell
end open

A decent introduction to AppleScript is here. A Google search on any specifics will find quite a few nice resources. A decent AppleScript intro book is AppleScript for Applications by Ethan Wilde, 0-201-71613-5.

[ Parent ]

Tried it (2.40 / 10) (#23)
by dennis on Sun Apr 04, 2004 at 02:47:13 PM EST

I've messed around with Cocoa/ObjC a bit, and I have to confess I didn't quite "get it."

My background is .Net/Java. Things that were irritants to me:

1) No garbage collection. Manually handling the reference count is doable, but adds mental cycles and lines of code that, to me, just get in the way. (Garbage collection introduces extra difficulties with non-memory resources, but there are a lot more memory resources than other types.)

2) The interface/implementation files, as in C/C++. Not necessary in my usual languages. Again, strikes me as extra code/busywork.

3) The difference between method and message syntax was sometimes irritating. I just want to ask an object to do something. Now I have to remember whether Something is implemented as a method or a message.

4) Interface Builder is the most elegant, beautiful gui builder I've ever seen. I love the little guidelines that pop up. But I'm not that keen on drawing connections between objects instead of doing that sort of thing in code. (Of course, that option is available.) I like being able to see in a sourcecode listing how everything fits together. Plus it just seemed weird actually instantiating objects at design time.

A lot of it pretty much boils down to "it's not what I'm used to." The extra capabilities of the language might turn my head, if I really knew how to take advantage of them...I'm probably too stuck in my current mindset to see it. A "Design Patterns in Obj-C" book would probably help a lot.

(For now, on the project I was considering it for, what I really need to do is replace the text storage model in a text editor. Thought that'd be doable in Cocoa, might be but it looks like it's not really designed for that, while the Swing text system is. Also, didn't look like Gnustep was up to speed on the text editing, and I'd prefer to be crossplatform if I can.)

2) Interface/implementation (none / 0) (#25)
by liquidcrystal3 on Sun Apr 04, 2004 at 04:20:27 PM EST

This separation is actually quite handy as the interface gives you a good overview of your class; showing what methods it'll respond to and what variables it holds. Other classes that import the interface 'know' what methods it'll respond to and they also know what to expect in return from them (whether it be a float, integer, reference to another object, etc).

[ Parent ]
Make it automatic (none / 1) (#30)
by dennis on Sun Apr 04, 2004 at 07:20:21 PM EST

the interface gives you a good overview

So keep the interface, but generate it automatically. Don't make me type things twice, that's what computers are for.

Ie., you could make me happy on this issue just by enhancing the IDE, not changing the language. It'd be a pretty simple text editor feature to implement, I would think.

[ Parent ]

A partial solution (none / 0) (#46)
by Sqeegee on Mon Apr 05, 2004 at 02:38:22 PM EST

A sort of half-way-there solution is to have Interface Builder generate your source files files for you. It's clunky, but it kinda works.

[ Parent ]
Okay (none / 1) (#47)
by mcc on Mon Apr 05, 2004 at 02:52:05 PM EST

# Integrate this into your build process, if you can figure out
#   how; if Xcode has documentation, I've never found it.
# Note that this assumes .h files will live in the same directory
#   as the .m files, and if there's a corresponding .h file there
#   already it WILL be stomped. Also note you MUST put the
#   #import classname.h line in the .m file for the compiler.
# The first thing in the @implementation needs to be a /** */
# beginning with a line stating ": superclass" (if any)
# followed by all field declarations (if any)

use strict;

FILE: foreach my $infile (@ARGV) {
    my $outfile = $infile; my $contents;
    $outfile =~ s/\.m$/\.h/
        or (print STDERR "$infile not an objc file!\n"
        and next FILE);

    open(IN, $infile)
        or (print STDERR "Could not open $infile to read!\n"
        and next FILE);
    open(OUT, ">$outfile")
        or (print STDERR "Could not open $outfile to write!\n"
        and next FILE);
    { local $/; $contents = <IN>; } close(IN);

    foreach my $import ($contents =~ /^\s*#\s*import\s*[\<\"]([^\>\"]+)/mg) {
        print OUT "#import \"$import\"\n" unless ($outfile =~ /$import$/);

    foreach my $class ($contents =~ /\@implementation\s+(.+?)\@end/sg) {
        $class =~ s/^(\w+(?:\s*[\<\(][^\>\)]+[\>\)])*)//;
        my $name = $1; my ($super, $fields);
        if ($class =~ s/^\s*\/\*\*\s*(\:\s*\S+)?//s) {
            $super = $1;
            die "FAILURE: $class /** */ block unterminated?"
                unless ($class =~ /;\s*\*\//s);
            until ($class =~ s/^\s*\*\///s) {
                $class =~ s/\s*([^;]*;)//s;
                $fields .= "$1\n";
        print OUT "\n\@interface $name$super\n";
        print OUT "{\n$fields}\n" if ($fields);
        while ($class =~ s/^.+?([\-\+])\s*(\S*)\s*\{//s) {
            print OUT "$1 $2;\n";
            my $method = $2;
            my $block = 1;
            while ($block) {
                die "FAILURE: $class method $method unterminated?"
                unless ($class =~ s/^[^{}]+([{}])//s);
                if ($1 eq "{") { $block++ } else { $block-- }
        print OUT "\@end\n";

[ Parent ]

Some responses. (2.83 / 6) (#26)
by mcc on Sun Apr 04, 2004 at 04:28:10 PM EST

1) No garbage collection.

Welcome to every C-derivative language previous to Java! If this bothers you, use Java instead of ObjC. Both work with Cocoa. One of the main reasons for offering the choice is so that coders can decide how close to the hardware they want to be.

2) The interface/implementation files, as in C/C++. Not necessary in my usual languages. Again, strikes me as extra code/busywork.

Welcome to every C-derivative language previous to Java! Is it a little annoying? Yeah. But they do have a reasonable purpose for existence. This way, you can distribute someone the interface file, allowing them to link against your objects, without having to distribute the entire source code for the object. Java gets around this by embedding the interfaces in the .class files; I don't know how .NET does it. Java's version is more convenient than ObjC's in that you don't have to maintain two files per class; ObjC's is more convenient in that the interfaces are immediately human-readable. It's just a design decision.

Objective C has additional reasons for this that C++ doesn't; due to the dynamic nature of the ObjC runtime, an interface more or less describes a "contract"-- almost as if each one were a java interface which the class implementations implement-- which the runtime might, if it really really wanted to for some reason, switch out the underlying implementation for at any time.

Anyway, if this really annoys you, be aware that XCode (recent versions of ProjectBuilder) have a button to automatically switch the current window back and forth between corresponding .c|.m|.cpp and .h|.hpp files. That helps a bit.

3) The difference between method and message syntax was sometimes irritating. I just want to ask an object to do something. Now I have to remember whether Something is implemented as a method or a message.

... I'm a bit confused. What's the difference? Methods are messages. Perhaps by "methods" you mean C-style functions? That's easy enough to keep separate; functions don't have target objects, they're just functions, and you shuld probably only be seeing them when interfacing with legacy C code... What exactly did you mean?

A lot of it pretty much boils down to "it's not what I'm used to."

That's not really something Apple can do anything about...

I'm probably too stuck in my current mindset to see it. A "Design Patterns in Obj-C" book would probably help a lot.

...that is. Apple's documentation is far, far behind where it should be and is something of an embarrasment.

(For now, on the project I was considering it for, what I really need to do is replace the text storage model in a text editor. Thought that'd be doable in Cocoa, might be but it looks like it's not really designed for that,

If I understand what you're saying, you should definitely be able to do that. Look into ".services"...

Also, didn't look like Gnustep was up to speed on the text editing,
and I'd prefer to be crossplatform if I can.)

...though I don't think that will be an option if you're trying to crossdevelop with Gnustep.

Aside from that, the absurd meta-wankery of k5er-quoting sigs probably takes the cake. Especially when the quote itself is about k5. -- tsubame
[ Parent ]

Interfaces (none / 1) (#29)
by dennis on Sun Apr 04, 2004 at 07:17:26 PM EST

Welcome to every C-derivative language previous to Java!

Yes, I'm aware of that...my response: welcome to the 21st century :) However, I'm not seriously trying to dis the language, just mentioning a few relatively minor points that bugged me....Java needs interfaces because it's statically compiled. With Obj-C being so dynamic, are they really necessary?

Must be mis-remembering something on my third point, maybe I was looking at the "Obj-C++" a few people have mentioned.

Thanks for the ".services" tip, I'll look it up.

[ Parent ]

This reply is probably unhelpful (none / 2) (#34)
by mcc on Sun Apr 04, 2004 at 11:16:53 PM EST

Java needs interfaces because it's statically compiled. With Obj-C being so dynamic, are they really necessary?

First off, ObjC is dynamically bound but it still tries to offer typechecking. It's just that type/method violations are viewed as warnings, not errors. Second off, ObjC objects, whatever they look like, are firmly based on C structs and while the method bindings may not be compiled statically, the objects themselves certainly are (for example, the compiler needs to know their size). This, of course, does not offer any explanation as to why the .h files could not be automatically generated-- there's no reason why they couldn't-- but it does give a good argument for the .h files to exist in the first place.

Yes, I'm aware of that...my response: welcome to the 21st century :)

This is unfortunately the biggest problem with Objective C: It remains firmly rooted in 1985. :) You'd think Apple could update it a little, but ah, such is life.

Must be mis-remembering something on my third point, maybe I was looking at the "Obj-C++" a few people have mentioned.

That would explain things nicely, actually. Keep in mind that ObjC++ is a compatibility tool to allow ObjC code to access C++ libraries and vice versa. Using it on purpose is NOT good coding practice and if you do so you may well deserve what you get :)

Aside from that, the absurd meta-wankery of k5er-quoting sigs probably takes the cake. Especially when the quote itself is about k5. -- tsubame
[ Parent ]

garbage collection (2.75 / 4) (#28)
by pb on Sun Apr 04, 2004 at 05:33:42 PM EST

There's no reason why you can't do garbage collection in C or C++, I might add.
"See what the drooling, ravening, flesh-eating hordes^W^W^W^WKuro5hin.org readers have to say."
-- pwhysall
[ Parent ]
Hmm (3.00 / 5) (#39)
by Julian Morrison on Mon Apr 05, 2004 at 08:58:25 AM EST

1) You use autorelease. That cuts away half the C/C++ problems because it takes care of the "who should free the object" problem. Basically, an autoreleased object remains in memory until the end of the current runloop cycle (ie: when your GUI code returns), and it can be reinstated before then with a "retain". So, when passing objects you don't intend to keep yourself, you call autorelease, the reciever always calls retain, and can call release whenever it's convenient. You're free to think about only the insides of objects. That's almost java-like in practise.

2) Seperate interfaces make a lot of difference for compilation speed because the implementation can change without forcing a rebuild of everything that uses the interface. This is why it's hard to use Java with "make", you have to parse classfiles to detect change cascades. Or like most java projects, you have to rebuild from scratch each time.

3) It should always be a method unless you're interfacing to someone else's library. (Hint: if it's confusing you, write a natural-ObjC wrapper around the C objects).

4) It's no more wierd than using a javabeans interface builder in java, in fact that's where they copied the idea.

[ Parent ]

Hmmhmm (none / 0) (#81)
by dennis on Wed Apr 07, 2004 at 07:13:07 PM EST

1) Yeah, I know, I'm just whining like a little girl about scattering those retain and release lines everywhere. I've got this pet theory that the more functional (and well-formatted) lines of code I can get on my screen, the more productive I am. Less cruft, more speed.

2) XCode does background compilation anyway...so it seems to me it could build interface files from the implementation, in the background, and figure out dependencies based on whether the hash changes. It shouldn't save compilation time by making me type stuff twice and manually keep things in sync.

4) Is Interface Builder really that new? I always assumed that was a Next leftover too, maybe not.

[ Parent ]

I'm quite proud of using a proprietary OS. (1.30 / 20) (#31)
by elenchos on Sun Apr 04, 2004 at 08:28:25 PM EST

The feature I take the most pride in is the ability to get actual work done. It's interesting to learn that there are users who are ashamed, to some degree, of this functionality.

I suppose you could emulate a non-proprietary operating system by occasionally deleting some random system file something. It's a weird thing to wish for, to be sure, but to each his own.


Talk about a weak-ass. (none / 3) (#41)
by Mr.Surly on Mon Apr 05, 2004 at 10:38:16 AM EST

You might as well have worn a name tag that said "Hi, my name is ... Troll"

[ Parent ]
No (1.00 / 4) (#51)
by Linux Sucks Balls on Mon Apr 05, 2004 at 05:26:31 PM EST

That would be like you wearing a nametag that says "I'm a marginalized longhaired white kid who listens to death metal and wears all-black clothes and hasn't bathed in 10 days and has cum stains on his trousers from masturbating to ESR's Sex Tips For Geeks." Entirely redunant.
"Linux works its hardware harder than Unix does..." -- Eric S. Gaymond
[ Parent ]
Glad you agree. (none / 2) (#53)
by Mr.Surly on Mon Apr 05, 2004 at 05:52:36 PM EST

[ Parent ]
as much as I enjoyed adequacy (1.00 / 7) (#44)
by phred on Mon Apr 05, 2004 at 02:18:52 PM EST

I do remember you as one of the marginalized no talent losers bathing in the reflected limelight of the real talent there. As you continue your career of loserdom, you seem to be picking up no additional ability. Perhaps adequacy was the "height" of your "career", and your mere leeching of the adequacy namesake just might be as good as it gets for you.

However, once you started posting here at k5 and elsewhere, one might have hoped you'd look around at the new generation of online discourse, but no, its just the same tired old game with you. Sometimes I wonder how bad it would be to have to ride the tired old horse that you seem to be on.

Oh well, at least you had some glory days back then to cling to.

[ Parent ]

Would you mind keeping this in the diary section? (1.60 / 5) (#48)
by elenchos on Mon Apr 05, 2004 at 04:15:39 PM EST

People who are reading this thread are interested in a technology article about Coco and Objective C. It is not about Adequacy.org. It is not about me. It sure as hell isn't about you.

So if you want to talk about me, why not put your comments into my diary, which is all elenchos, all the time.

In short, you are off-topic, and no one cares. HAND.

[ Parent ]

just to clarify things (none / 3) (#64)
by phred on Tue Apr 06, 2004 at 08:16:10 AM EST

While this is a marvelous article, I felt I could go off topic for just a bit to offer some advice to you. As one of the "me too"'s at adequacy, you were viewed by many as one of the pet lamers of the true talents at that marvelous site. Given the bulk of mediocracy you insist upon posting here, I just felt myself to be in a generous mood and offer a truly unbiased opinion of what you view to be "contributions". I didn't want to detract from the marvelous technology article, but I really felt sorry for you here and felt compelled to shine some light your way.

[ Parent ]
IAWTAP (none / 2) (#75)
by Phillip Asheo on Tue Apr 06, 2004 at 03:10:23 PM EST

And I am an out-and-proud iBook G4-using MacOS X liking Steve-Jobs-every-word-hanging-onto MAC BIGOT. Lets face it, PCs are for lazy people. If you want to get some actual paid-for work done, Macs are the only way forward.

"Never say what you can grunt. Never grunt what you can wink. Never wink what you can nod, never nod what you can shrug, and don't shrug when it ain't necessary"
-Earl Long
[ Parent ]

Be aware (1.10 / 10) (#36)
by problem child on Mon Apr 05, 2004 at 02:40:43 AM EST

Your app will work on less than 5% of the desktop market.

but you will have a better chance at exposure (none / 2) (#43)
by modmans2ndcoming on Mon Apr 05, 2004 at 11:58:59 AM EST

think about it like this...you are a nobody....so you develop an app on OS X and it rocks...everyone who is in your market loves it and dumps their other solution for yours...you then make a windows version and begin to sell a lot to the windows world.

or you could just make a windows app and get lost in the plethora of "Me Too" apps on download.com.

[ Parent ]

Actually make that 10% to 100% (none / 0) (#83)
by egkamp on Thu Apr 08, 2004 at 12:06:00 AM EST

Actually make that 10%, considering that Linux has objc and (depending on who you ask) Linux either just passed (or is just about to pass) Apple's 5%. If you include cygwin then you can even run objc on that *other* ubiquitous OS.

[ Parent ]
Objective C... (1.60 / 5) (#37)
by ksandstr on Mon Apr 05, 2004 at 07:11:10 AM EST

I've got just one word for ObjC: YECH. The syntax is still as I remember from sometime back in 1996, the last time I tried it (i.e. bloody repugnant), and I expect that writing applications in it is still as painful as with any "we don't need no steenking templates, here, have some RTTI instead" language. The most frustrating thing about it is that ObjC comes so very close to doing the right thing wrt extending stock C with class/object/methodcall syntax but falls just a little bit short.

Though the method call syntax is still rather nice, apart from the re-use of the array indexing brackets for entirely evil purposes. I've always wanted labelled function and method call arguments (like Python, Smalltalk, Common LISP and ObjC have, for instance) in C and C++, but I suppose that would be just a little bit too radical a change for the C standardization people to consider :-)

C is tied to the machine (none / 0) (#70)
by repp on Tue Apr 06, 2004 at 01:20:39 PM EST

I was going to write about why I thought your idea stinks, but now that I've thought about it, I can't see why it wouldn't work.  The header files can connect the order of parameters to the name, and so you could have labelled parameters in C.

Of course, it would be a massive undertaking, since every major library has functions with anonymous parameters.  Isn't "extern foo(int);" currently allowed?

[ Parent ]

I'd rather (none / 1) (#38)
by hading on Mon Apr 05, 2004 at 08:45:02 AM EST

just use Smalltalk.

Perl (1.00 / 4) (#42)
by Alhazred on Mon Apr 05, 2004 at 11:36:23 AM EST

For that matter I could have said 'Python' but I just never bothered to learn it (how many variant syntaxes of Perl do we really need...).

Basically you've got the same advantages, a huge library of classes to choose from, several very good IDEs and GUI construction toolkits, like perlqt etc. and the ability to simple stuff with simple tools. Thats the problem with these big monolithic development environments, they impose too much overhead when all I need are 30 lines of code!

And on the large scale project side of the fence I'm not at all convinced you could build things like large equity trading apps with Objective-C. (not that you would probably build them in perl either, but C++ has its place!).
That is not dead which may eternal lie And with strange aeons death itself may die.

Well. (none / 0) (#74)
by Phillip Asheo on Tue Apr 06, 2004 at 03:08:02 PM EST

I'm not at all convinced you could build things like large equity trading apps with Objective-C.

If you can do it in smalltalk-80, COBOL, perl, or bourne shell (yes, really), I see little reason why Objective-C could not cope. Most applications that claim scalability are not truly scalable in a linear sense, rather they scale up to some fixed point which is considered sufficient 'headroom' for the expected volumes.

"Never say what you can grunt. Never grunt what you can wink. Never wink what you can nod, never nod what you can shrug, and don't shrug when it ain't necessary"
-Earl Long
[ Parent ]

Orc Software (none / 0) (#78)
by wocko on Wed Apr 07, 2004 at 02:21:26 AM EST

This equity derivatives trading system, Orc Software, definitely used to be written in Objective-C and run on NeXT workstations. Not sure if that is still the case.

[ Parent ]
Oh, I dunno (none / 0) (#80)
by dennis on Wed Apr 07, 2004 at 06:47:08 PM EST

Cocoa is built with Objective-C, it's kinda big.

And Obj-C is modelled on Smalltalk, which (not counting Squeak) is generally used for large financial applications, and quite successfully from what I've read...in fact, the Smalltalk people are kinda cocky about it.

[ Parent ]

Uhhhh (none / 0) (#85)
by Alhazred on Fri Apr 09, 2004 at 04:03:11 PM EST

Market center data applications and large trading desk applications. Its a pure C++ world out there...

For instance we're maintaining and extending applications with MANY millions of lines of code, fully distributed load balanced, fault tolerant, and with often times 1000's of users (or more). And yes they ARE linearly scalable!

Consider, our main code base was used to build the Telerate terminels, BRUT, Patriot, etc. Trust me, its a total efficiency-freak kind of world ("Oh don't use those nasty virtual functions, they cost you 1% performance...').
That is not dead which may eternal lie And with strange aeons death itself may die.
[ Parent ]

Don't forget the big boy on the block (none / 0) (#88)
by X-Nc on Fri Sep 24, 2004 at 07:21:04 PM EST

COBOL still rules the data. Banks, Airlines, Wall St., virtually every Government... It's all about the data. Not only is there more "legacy" COBOL code than all other languages combined (in number of lines coded) only C has more new development than COBOL. Yes, it's the #2 langiage for new code being writen. And believe me, this isn't your daddys COBOL. I't got OOP that's as good or better than C++ and lots of very modern aspects. Just check out the spec.

No, COBOL is not what you'd use to build an C/S GUI app but for pushing large (and I mean LARGE) amounts of data it's still the best tool for the job.

As soon as theKompany gets the GUI plug-in for Kobol I'll be all set.

Aaahhhh!!!! My K5 subscription expired. Now I can't spell anymore.
[ Parent ]

What a waste. (1.75 / 8) (#50)
by ninja rmg on Mon Apr 05, 2004 at 04:41:11 PM EST

Another implementation of the same old thing. Graphical interfaces haven't changed in fifteen years, except in that they look better now. Sure you have tabs and those little things that appear when you hover over buttons, but those are trivial additions.

Every different graphical interface system is the same damn thing written in a different langauge or with some different harebrained programming "paradigm" in mind -- callbacks, signals, etc. This is what these engineers spend their time on. Writing new APIs that do the same thing as all the others. Writing programs that do something that's just a special case of some other program written in a different language or different paradigm or whatever somewhere else.

Same thing every time. It's monkey work. Why do people go to school to learn this? It's something you could teach a child to do. You could place them all in a little room and beat a drum as they type. Even better: You could do it in Indonesia!

Yes, you could be working on new algorithms, working on pushing the frontier of knowledge, making a better tomorrow full of newer better computing, but no. Same old interface. Same old language. Same state of computing. The only thing that goes forward is hardware. New processors, faster memory and disks, faster networks (hence the internet)... But oh no no no. We'll still write our programs in C (or some variant thereof, whether it be C++, Java, C#, Objective C, or whatever).

Every other field of engineering brings new technologies. Every other field of science brings new discoveries and progress everyday. But Computer Science? Nothing. Fifteen years and still the same damned thing.

Not true (none / 1) (#62)
by TuringTest2002 on Tue Apr 06, 2004 at 06:50:11 AM EST

There are huge research and quite new achievements in Human-computer interaction and usability. The problem is not that there is nothing new, but that it is not adopted by industry because of an overwhelming inertia. Software developers are really, really conservative people in this respect!

[ Parent ]
Well... (none / 0) (#86)
by epepke on Fri Apr 09, 2004 at 05:28:57 PM EST

Doing new things is one thing. Doing old things right is another. I've seen a lot of "visual" programming paradigms over the years, and Interface Builder is the only one I can stand, because it does what I want and then gets the hell out of the way. So that's something.

The truth may be out there, but lies are inside your head.--Terry Pratchett

[ Parent ]
[objc retain]; (none / 2) (#54)
by Graymalkin on Mon Apr 05, 2004 at 06:27:16 PM EST

Since being introduced to Obj-C around 1999 I've been a really big fan of it. It is simple yet extremely flexible and for me a much easier language to work with than Java or C++. I really love dynamic binding, third parties can come along and replace a first party library with a third party one and nothing will break; anything using the first party library will gain all the advantages of having the third party library. Weak typing can also be very useful if you're careful with it. I tend to agree with Guido van Rossum with regards to typing, weak typing lets you find typing error in a more controllable way rather than banging your head at compile time. It also allows you to change bits and pieces of a program around without having to change everything around.

There's several good Obj-C articles floating around the intarweb. wrote one a billion some years ago before Apple bought out NeXT. It is a nice comparison between C++ and Objective-C which describes both languages advantages and disadvantages. Linux Journal carried an article a few years ago discussing Obj-C with an eye towards comparing it to C++. I figure both of these are apropos as most people here probably have much more exposure to C/C++ than SmallTalk and its kin. There's a nice interview on atrima.com with Guido van Rossum with regards to strong versus weak typing which I suppose is germane to a discussion of Obj-C.

On typing: that's slightly backwards (none / 1) (#72)
by HereticMessiah on Tue Apr 06, 2004 at 01:43:46 PM EST

It's dynamic typing he was talking about. Weak typing is horrible. One of the definite improvements C++ made over C was strengthening its typing.

Python, if I remember correctly, uses strong dynamic typing. That's what makes something like StarKiller possible.

Static typing can be a right pain. You end up specifying details that the compiler should be able to infer from the code. Oh, if only more statically typed languages used type inferrence like (S/O'Ca)ML and Haskell...

That's why C's type system sucks. It's both weak and static. <smack!>

Disagree with me? Post a reply.
Think my post's poor or trolling? Rate me down.
[ Parent ]

I hope (none / 2) (#65)
by Zealot on Tue Apr 06, 2004 at 10:35:19 AM EST

that I speak for other conservative minded C coders, when I say: "eew"

Smalltalk-80 gives you all this (none / 2) (#73)
by Phillip Asheo on Tue Apr 06, 2004 at 03:02:52 PM EST

And then some. Why would you compromise? Why doesn't Jobs make Smalltalk the core of MacOS X application development? That would rock!!!

"Never say what you can grunt. Never grunt what you can wink. Never wink what you can nod, never nod what you can shrug, and don't shrug when it ain't necessary"
-Earl Long

Because it's interpreted, thus slow as hell? n/t (none / 1) (#82)
by der on Wed Apr 07, 2004 at 10:47:49 PM EST

[ Parent ]
Given that (none / 1) (#84)
by hading on Thu Apr 08, 2004 at 09:56:38 AM EST

some Smalltalks have been compiled for, oh, twenty years, this seems like a strange objection.  Even the ones which don't do any native compilation (e.g. Dolphin) are plenty fast for a large variety of applications:

The Interpreter is Dead (slow). Isn't it?

In fact, somewhat ironically, this article (1999) begins with the paragraph:

"Smalltalk is not interpreted.  It's been using a JIT for years.  There hasn't been a commercial Smalltalk with an interpreter for at least a decade."

So some people apparently have exactly the opposite misconception.

[ Parent ]

Classed based OO languages (none / 0) (#76)
by QuantumG on Tue Apr 06, 2004 at 08:51:19 PM EST

ewww.. even Smalltalk, which is the best of the lot, has a funky syntax that is counter-intuitive and this completely arbitary distinction between "inheritence" and "instantiation".

Gun fire is the sound of freedom.
Cocoa (none / 1) (#77)
by kjb on Tue Apr 06, 2004 at 11:45:28 PM EST

Apple also has a bunch of information, including their own Cocoa tutorial, on their developer connection website.

Now watch this drive.

Okay, but riddle me this... (none / 0) (#79)
by porkchop_d_clown on Wed Apr 07, 2004 at 09:35:30 AM EST

  1. Can I write Cocoa applications that access the IOKit?
  2. Is there any real documentation on the proper way to access peripherals from the !@#$!# IOKit? - uncommented sample apps can only take me so far.

Will we line up for Grand Theft Auto 5 if it's the exact same thing, only with prettier texture-mapped bruises on the whores? -- David Wong
Introduction to Cocoa with Objective-C | 88 comments (69 topical, 19 editorial, 4 hidden)
Display: Sort:


All trademarks and copyrights on this page are owned by their respective companies. The Rest 2000 - Present Kuro5hin.org Inc.
See our legalese page for copyright policies. Please also read our Privacy Policy.
Kuro5hin.org is powered by Free Software, including Apache, Perl, and Linux, The Scoop Engine that runs this site is freely available, under the terms of the GPL.
Need some help? Email help@kuro5hin.org.
My heart's the long stairs.

Powered by Scoop create account | help/FAQ | mission | links | search | IRC | YOU choose the stories!