2011-12-16 64 views
4

我的Obj-C類是一個C數組(我沒有興趣使它成爲Obj-C屬性)。夠簡單。現在在我的類的init方法中,我希望使用C數組速記init爲此數組創建一些值,如下面的.m中所示。但我相當積極,這是由相同的名稱創建一個局部變量,而不是初始化我的實例變量。我不能把我的數組init放在接口中,我不能在實現中聲明一個ivar。我是否堅持做某種深層複製或者我有其他選擇?初始化是C數組的Objective-C類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; 
} 

回答

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)); 
+0

非常好,謝謝! – rob5408 2011-12-16 15:25:45