Tustin2121
Tustin2121

Reputation: 2176

Objective C - Access another instance's instance variables?

Is it possible to access another instance's variables, given that we're working in the same class?

Or, in other words, can you do this Java code (which works in Java, I've done it before) in Objective C:

class Matrix {
    private int mat[] = new int[16]; //wouldn't be a pointer in C

    public Matrix (Matrix m){
        for (int i = 0; i < 16; i++){
            this.mat[i] = m.mat[i]; //<-- this here
        }
    }
}

Given that arrays cannot be properties in Objective C, I can't make mat[] into a property. Is there any way to do this then?

Upvotes: 2

Views: 549

Answers (4)

Adam Rosenfield
Adam Rosenfield

Reputation: 400692

You can do it perfectly fine, you just can't make the instance variable (ivar) into a property:

@interface Matrix : NSObject
{
@private
    int mat[16];
}
- (id) initWithMatrix:(Matrix *)m;
@end

@implementation Matrix
- (id) initWithMatrix:(Matrix *)m
{
    if ((self = [super init]))
    {
        for(int i = 0; i < 16; i++)
            mat[i] = m->mat[i];
        // Nota bene: this loop can be replaced with a single call to memcpy
    }
    return self;
}
@end

Upvotes: 3

hotpaw2
hotpaw2

Reputation: 70743

Arrays can't be properties. But pointers to an array of C data types can. Just use an assign property, and check for NULL before indexing it as an array.

Upvotes: 0

rpetrich
rpetrich

Reputation: 32346

The closest analogy would be a readonly property that returns int *:

@interface Matrix : NSObject {
@private
    int values[16];
}
@property (nonatomic, readonly) int *values;
@end

@implementation
- (int *)values
{
    return values;
}
@end

For a Matrix type, you should really be using a struct or Objective-C++; all the method dispatch/ivar lookup will add a lot of overhead to inner loops

Upvotes: 1

mportiz08
mportiz08

Reputation: 10328

You could use an NSArray that holds NSNumbers instead of a regular old c int array--then you could use it as a property.

something like this maybe:

self.mat = [NSMutableArray arrayWithCapacity:16];
for(int i = 0; i < 16; i++) {
  [self.mat addObject:[NSNumber numberWithInt:[m.mat objectAtIndex:i]]];
}

Upvotes: 3

Related Questions