2

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?

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is the exact thing I was looking for: a way to access it without making it a property (and therefore public). I didn't know you could do a pointer deference in Objective-C and with an Objective-C object. (And thank you for the good note). :)
3

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]]];
}

1 Comment

That seems a bit bloated, plus the eventual goal is to pass the array directly to OpenGL, which would most likely require some conversion with this scheme.
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.