初始化Objective-C类的C数组实例变量

4
我在我的Obj-C类中有一个C数组的ivar(我不想将其变成Obj-C属性)。很简单。现在在我的类的init方法中,我想使用如下所示的C数组速记初始化种子值。但是我非常确定这会创建同名的局部变量而不是初始化我的实例变量。我不能将我的数组初始化放在接口中,也不能在实现中声明ivar。我是否只能进行某种深层复制或者还有其他选择?
#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;
}
1个回答

5

你说得对。你正在初始化一个局部变量,这会遮盖实例变量。你可以初始化一个局部数组,然后使用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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接