Lefora Free Forum
login join
Loading
558 views

Possibly stupid question?

Page 1
1–4
?
63 posts

Hi all

This question may be stupid..

but why can't I declare an object like this:
Object instance = [[Object alloc] init];

Instead why do I have to do
Object *instance = [[Object alloc] init];

Just curious..

__________________
kompilesoft

come and see my website! it's real cool reviews
?
288 posts

Because you can't actually create an object!  What you do is to allocate an object in memory (from the heap) and you have a pointer to it.  That's what Object* instance means!

If you created an object on the stack with:
Object deadOnArrival ;

several things would happen including:
1) the object would be on the stack
2) the object wouldn't call alloc or init
3) the object will go out of scope at the end of the current block    ( the } syntax ) and would not call its release or dealloc methods
4) to call a method on that object you'd have to say [&object myMethod....]; (not nice at all)
- in short you're in deep trouble.

C++ addresses all of those matter - however you're in the land of Obj/C and the rules of C apply to Obj/C.

I agree that having to put the * thing on the line in which you declare is irritating.  However, just accept it and you'll soon be happy.  Fight it and you'll be sorry!


__________________
?
63 posts

Wow, interesting. It almost seems natural though, to have *instance *thang. It looks cool.

__________________
kompilesoft

come and see my website! it's real cool reviews
?
288 posts

I personally always write that as:
NSObject* instance = bla bla

and not as:
NSObject *instance = bla bla

The name of the variable is called instance (and it's of type NSObject*).  The name is NOT called *instance (of type NSObject).  Sadly, all the Apple code uses the *instance style of declaration.

In the "C" language you can declare things like this:
int fred, *pointerToFoo, vomit, nonesense, *anotherWeePtr;

In my opinion there 2 serious defects of C language demonstrated here:
1) You shouldn't be allowed to declare more than one variable at a time.
2) Even if you could declare multiple variable, I would not allow the * on the variable name - I'd put it on the type.  So I'd have:
int fred, vomit, nonesense ;
int* pointerToFoo, anotherWeePtr;

However, leaving aside my dislike of the *instance thing, let's return to the NSObject*.  I agree it's kind of odd.  However that's C.  You'll have to accept it - it isn't going to change.

__________________
Page 1
1–4

Locked Topic


You must be a member to post in this forum

Join Now!