Re: ?*
Re: ?*
- Subject: Re: ?*
- From: Simon Stapleton <email@hidden>
- Date: Sun, 24 Jun 2001 14:27:34 +0100
Subject: Re: *?
Cc: email@hidden
To: email@hidden
On Friday, June 22, 2001, at 10:22 , Finlay Dobbie wrote:
all obj-c objects are pointers, they are never statically allocated.
myArray is actually a pointer to an NSMutableArray. i'm surprised your
C book doesn't have more on pointers, they're a fundamental thing that
you need to understand, and are not terribly easy to grok in the
beginning.
-- Finlay
On Friday, June 22, 2001, at 07:06 pm, email@hidden wrote:
which says that myArray is of type "NSMutableArray" instead of generic
type "id". But there is no explanation that I can find as to what
the * does or means in the first two examples. My copy of Kernighan
and Ritchie just came and I looked there, but all I could find was a
usage somewhat similar on page 94 that uses the * to indicate that an
argument is a pointer to a type. So, all I can guess is that in the
example:
To add a little to that, usage like
NSMutableArray *myArray; //
<dataType><space>*<variableNameWithNoSpaceInFront>
is just the way that most programmers are used to reading this
particular idiom. As far as the compiler is concerned you can put spaces
before the star, after the star, before and after, or neither before or
after. It's readability and whatever helps your thinking.
Another thing which might be causing confusion is that the type 'id' is
a pointer. What it means literally is 'a pointer to a subclass of one
of the objective-c root classes, but I'm not sure which'. This is
similar to C's 'void *' (pointer to _something_) in concept.
So...
id myArray;
will behave in exactly the same way as
NSArray * myArray;
as long as myArray is either an NSArray or some subclass thereof.
However, if you try to set myArray to be, for example, an object of type
NSWindow *, the NSArray * declaration will pick this up as invalid at
_compile time_, whereas the problem wouldn't be picked up until runtime
where the id declaration is in place, and only then if some unavailable
method of NSArray is being called on the NSWindow object.
A general rule-of-thumb is that you should keep declarations at the
level of the lowest common denominator of the possible contents. Which,
on rereading, makes buggerall sense.
So, if you're going to store stuff in an NSMutableArray, and only ever
an NSMutableArray, declare as NSMutableArray *.
If you're thinking you may store stuff as an NSArray or an
NSMutableArray, use NSArray *.
And so on up the hierarchy.
The only time you should be using id is where you really _don't_ know
the type of the object. A good example of this is IBAction declarations,
where the sender could be anything.
Hope this was of some limited help
Simon