Reputation: 2982
I have an ivar in my Obj-C class that's a C array (I'm not interested in making it an Obj-C property). Simple enough. Now in my class's init method I'd like to seed this array with some values using the C array shorthand init as seen in my .m below. But I'm fairly positive this is creating a local variable by the same name and not initializing my instance variable. I can't put my array init in the interface and I cannot declare an ivar in an implementation. Am I just stuck doing some sort of deep copy over or do I have another option?
In GameViewController.h
#define kMapWidth 10
#define kMapHeight 10
@interface GameViewController : UIViewController
{
unsigned short map[kMapWidth * kMapHeight];
}
@end
In 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;
}
Upvotes: 4
Views: 725
Reputation: 421988
You are right. What you are doing is initializing a local variable, shadowing the instance variable. You can initialize a local array and memcpy
it to the instance variable:
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));
Upvotes: 5