Re: C code in Object-C?
Re: C code in Object-C?
- Subject: Re: C code in Object-C?
- From: David Trevas <email@hidden>
- Date: Mon, 9 Jul 2001 09:50:40 -0500
I am working my way through the Learning Cocoa book, and encountered a
code example that mixes C code in Object-C. All the other code so far
has been Object-C syntax, but suddenly I see C code out of no where. I
don't understand why the writer decided to do this. I don't see the need
to use C code instead of Object-C here, unless the writer decided to
just show it's possible to mix code. It's just confusing. I don't even
know why standard C code would work with the compiler?
I'd appreciate any clarification regarding this matter.
Objective-C is truly a superset of C meaning you can put as much C code
as you like into an Objective-C program and the compiler will have no
problem. In fact, I sometimes use Project Builder to write pure C code
(you can too if you choose the project called "Standard Tool" as the
type when you start a new project.)
Without seeing where the variables come from in the example you provide,
I cannot comment on why the author chose to write C functions in this
case instead of ObjC methods. However, sometimes it is more efficient
and easier to understand a C function than the whole process of creating
an object just to create that method, that is, you can be
object-oriented without being object-obsessed. A good example of being
object-obsessed comes from JavaScript where there are no trig functions
(sine, cosine, etc.) -- you have to use methods of the Math object.
This serves no purpose except to decrease readability.
Furthermore, there is already some standard C in Cocoa already.
NSPoint, NSSize, NSRect and NSRange are all C "structs" and there are
functions like NSMakePoint() that are C functions. From a practical
standpoint, the fact that ObjC is C plus the object-oriented additions
is a major advantage of the language since tons of C code (and C
programmers) are out there that can be resources for your ObjC
projects. The downside, I suppose, is that since it is the programmer's
choice to create a function or a method, the decision may seem ambiguous
to someone reading the code (and particularly troubling for a
beginner). In the long run, it is probably better that "there is more
than one way to skin a cat" than to be locked into the "object-obsessed"
way of thinking.
Hope this helps and good luck.
Dave