Objective C - 访问另一个实例的实例变量?

时间:2011-05-07 04:40:15

标签: iphone objective-c c

是否可以访问另一个实例的变量,因为我们在同一个类中工作?

或者,换句话说,你可以在Objective C中执行这个Java代码(在Java中工作,我之前已经完成了):

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

鉴于数组不能是Objective C中的属性,我无法将mat[]转换为属性。有没有办法做到这一点?

4 个答案:

答案 0 :(得分:3)

你可以使用一个NSArray来保存NSNumbers而不是常规的旧c int数组 - 然后你可以将它用作属性。

这样的事情可能是:

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

答案 1 :(得分:3)

你可以完美地完成它,你只是不能将实例变量(ivar)变成属性:

@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

答案 2 :(得分:1)

最接近的类比是返回int *的只读属性:

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

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

对于Matrix类型,您应该使用struct或Objective-C ++;所有方法dispatch / ivar lookup都会给内循环增加很多开销

答案 3 :(得分:0)

数组不能是属性。但指向C数据类型数组的指针可以。只需使用assign属性,并在将其作为数组索引之前检查NULL。

相关问题