开发者

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 a开发者_StackOverflow社区rrays cannot be properties in Objective C, I can't make mat[] into a property. Is there any way to do this then?


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜