mahulst
mahulst

Reputation: 443

Variables of multiple instances are always the same

I not at all a pro at developing in C languages. Just experimenting with these things for fun. My problem is probably just a pointer/alloc issue, but I just cannot figure it out.

My problem is that when I create two instances of a class called Port and want to assign different values to a variable inside that instance. The value of product1 and product2, but when I change one of them, the other instances gets the same value. What I want of course is being able to define different values to the variables of each instance.

The variable are declared in the Port class like this:

NSObject *product1, *product2; 

And the method to change them is this one:

-(void) setProducts: (NSObject*)setProduct1 andTwo: (NSObject*)setProduct2
{
    product1 = setProduct1;
    product2 = setProduct2;
}

Inside the main I create the ports in the init function

   Port *port1 = [[Port alloc] init];        
    [port1 setProducts:@"uno" andTwo: @"dos"];       
    [ports addChild:[port1 getMenuItem]];    

    Port *port2 = [[Port alloc] init];
    [port2 setProducts: @"tres" andTwo: @"viero"];
    [ports addChild:[port2 getMenuItem]];

I hope I have informed you enough and that you can help out. If I need to add more information feel free to ask.

Upvotes: 0

Views: 148

Answers (1)

jscs
jscs

Reputation: 64002

It looks like you're saying those variables are declared something like this:

// Port.m

#import "Port.h"

NSObject *product1, *product2;

@implementation Port

// Method implementations...

@end

Which means that those are the Objective-C version of "class variables". Every instance of the class has access to them, but they're the same variable for every instance. If you want instance variables, you should put them in the class's interface declaration, like so:

@interface Port : NSObject 
{
    NSObject * product1;
    NSObject * product2;
}

// Declare methods...

@end

See also: Learning Objective-C: A Primer

Upvotes: 2

Related Questions