Unable to access variable from a different class in Cocoa
I have 2 classes in Cocoa, but am unable to access variables from one to the other.
Class1.h:
@interface MyClass : NSOpenGLView
{
int myVar;
}
@property (assign) int myVar;
Class1.m
@implementation MyClass
@synthetize myVar;
...
myVar=5;
Class2.m
MyClass *theClass=[MyClass alloc];
nb=theClass.myVar;
==> nb=0 (instead of 5), and I am sure that the 开发者_运维百科myVar=5 was executed.
What did I wrong ?
Thanks !
In Class2
, you are creating a new instance of MyClass
, rather than referring to an existing instance where you have previously set the myVar
property to 5.
It's also worth mentioning that, if you needed to create a new instance of MyClass
(that you don't), this line:
MyClass *theClass=[MyClass alloc];
should be:
MyClass *theClass=[[MyClass alloc] init];
From Allocating and Initializing Objects:
It takes two steps to create an object using Objective-C. You must:
- Dynamically allocate memory for the new object
- Initialize the newly allocated memory to appropriate values
An object isn’t fully functional until both steps have been completed. Each step is accomplished by a separate method but typically in a single line of code:
id anObject = [[Rectangle alloc] init];
精彩评论