V-Xtreme
V-Xtreme

Reputation: 7333

Declaring Object of one class into another class

I have class named Building :

@interface Building : NSObject
@property (nonatomic,retain)NSString* node;
@property (nonatomic,retain)NSString* subnode;
@property (nonatomic,retain)NSString* supernode;
@property (nonatomic,retain)Node *reference;
@end

I have another class named:Node

@property (nonatomic,retain)NSMutableArray* strArray;
@property (nonatomic,retain)NSString * strName;

I declared instance of Building from third class .I have set strName from third class by using the reference of the building:

   building.reference.strName=strVal;

But this giving me null value .How can i set this value by using the reference of the Building class.

Upvotes: 0

Views: 169

Answers (1)

Jhong
Jhong

Reputation: 2752

Make sure you are initialising reference in Building's -init method. For example (assuming Node also inherits directly from NSObject):

- (id) init {
    self.reference = [[Node alloc] init];
    return self;
}

In addition you could write a designated initialiser method to pass in an existing Node when initialising, e.g. -initWithNode: (Node)myNode. Then you would get your Building's -init method to call [self initWithNode:[[Node alloc] init].

Then to initialise a Building object, you can call [[Building alloc] init] (to get a Building with a blank Node) or [[Building alloc] initWithNode:myNodeObject] (to get a Building with a Node you already instantiated).

Note that if Node doesn't inherit directly from NSObject (which doesn't do anything in it's own init), you should call the superclass init routine as well, so your initialiser would become:

- (id) init {
    if(self = [super init]) {
        self.reference = [[Node alloc] init];
    }
    return self;
}

Upvotes: 1

Related Questions