初始化作为C数组的Objective-C类ivar

初始化作为C数组的Objective-C类ivar,objective-c,c,arrays,Objective C,C,Arrays,在我的Obj-C类中有一个ivar,它是一个C数组(我不想把它变成Obj-C属性)。很简单。现在,在我的类的init方法中,我想使用C数组速记init为这个数组添加一些值,如下面的my.m所示。但我相当肯定这是创建一个同名的局部变量,而不是初始化我的实例变量。我不能将数组init放在接口中,也不能在实现中声明ivar。我只是被困在做某种深度复制,还是我有其他选择 在GameViewController.h中 #define kMapWidth 10 #define kMapHeight 10

在我的Obj-C类中有一个ivar,它是一个C数组(我不想把它变成Obj-C属性)。很简单。现在,在我的类的init方法中,我想使用C数组速记init为这个数组添加一些值,如下面的my.m所示。但我相当肯定这是创建一个同名的局部变量,而不是初始化我的实例变量。我不能将数组init放在接口中,也不能在实现中声明ivar。我只是被困在做某种深度复制,还是我有其他选择

在GameViewController.h中

#define kMapWidth 10
#define kMapHeight 10

@interface GameViewController : UIViewController
{
    unsigned short map[kMapWidth * kMapHeight];
}

@end
在GameViewController.m中

- (id)init
{
    if ((self = [super init]))
    {
        unsigned short map[kMapWidth * kMapHeight] = { 
            1,1,1,1,1,1,1,1,1,1,
            1,0,0,0,0,0,0,0,0,1,
            1,0,0,0,0,0,0,0,0,1,
            1,0,0,0,0,0,0,0,0,1,
            1,0,0,0,0,0,0,0,0,1,
            1,0,0,0,0,0,0,0,0,1,
            1,0,0,0,0,0,0,0,0,1,
            1,0,0,0,0,0,0,0,0,1,
            1,0,0,0,0,0,0,0,0,1,
            1,1,1,1,1,1,1,1,1,1,
        };
    }
    return self;
}

你说得对。您所做的是初始化局部变量,隐藏实例变量。您可以初始化一个本地数组,然后
memcpy
将其初始化为实例变量:

static const unsigned short localInit[] = { 
        1,1,1,1,1,1,1,1,1,1,
        1,0,0,0,0,0,0,0,0,1,
        1,0,0,0,0,0,0,0,0,1,
        1,0,0,0,0,0,0,0,0,1,
        1,0,0,0,0,0,0,0,0,1,
        1,0,0,0,0,0,0,0,0,1,
        1,0,0,0,0,0,0,0,0,1,
        1,0,0,0,0,0,0,0,0,1,
        1,0,0,0,0,0,0,0,0,1,
        1,1,1,1,1,1,1,1,1,1,
};

memcpy(map, localInit, sizeof(localInit));