[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Life of instance variables?
From: |
Albert Chun-Chieh Huang |
Subject: |
Life of instance variables? |
Date: |
25 May 2003 13:49:48 +0800 |
User-agent: |
Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 |
Dear all,
My question is about instance variable. Let me explain in details:
Node and MyNode is two classes, their relationship is
MyNode : Node : NSObject, where MyNode is a subclass of Node.
In my code, there is only instances of MyNode, for Node is an abstract
class.
@interface MyNode : Node
{
some instance variables
}
- init;
@end
@interface Node : NSObject
{
int state; // Initial value as 14
}
- init;
- (void)receivePacket: (id)aPacket;
- (void)setNodeState: (int)aState;
@end
@implementation Node
- (void)setNodeState: (int)aState
{
state = aState;
}
@end
I create the instance of MyNode in another class, say Simulator, by:
aNode = [[MyNode alloc] init];
[aNode setNodeState: 1];
In the class Channel:
[aNode receivePacket: aPacket]; // aNode is an instance of MyNode
So I assume that when I call [aNode receivePacket: aPacket], state is
not possible to be 14 because the initial value won't be set again!
I'm sure that I didn't set it to 14 in other places. And now, I add
some NSLog in -[Node receivePacket:], I found that whenever I call
[aNode receivePacket: aPacket], "state" value is 14 not 1. Why did
this append?
I don't know why it happens. I studied this in "Object-Oriented
Programming and the Objective-C Language" manual from NeXT Developer's
Library, and I couldn't find the reason. The instance variable "state"
should be "inherited" from Node. And when I call
[aNode receivePacket: aPacket], the run-time system should find the
superclass of MyNode because MyNode doesn't have implementation of
receivePacket: method. Sorry, I'm really confused. Could anyone be
kind of telling me why? Thanks in advance.
Best Regards,
Albert
--
Chun-Chieh Huang, aka Albert | E-mail: jjhuang AT cm.nctu.edu.tw
黃俊傑 |
Department of Computer Science |
National Tsing Hua University | MIME/ASCII/PDF/PostScript are welcome!
HsinChu, Taiwan | NO MS WORD DOC FILE, PLEASE!
- Life of instance variables?,
Albert Chun-Chieh Huang <=