Initializing Objective-C to ivar class, which is an array of C

I have ivar in my Obj-C class that is an array of C (I'm not interested in making it an Obj-C object). Simple enough. Now, in my class initialization method, I would like to minify this array with some values ​​using a C string script, as shown in my .m below. But I'm pretty sure that this creates a local variable with the same name and does not initialize my instance variable. I cannot put my init array in the interface, and I cannot declare ivar in the implementation. Am I just stuck making some kind of deep copy, 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; } 
+4
source share
1 answer

You're right. You are initializing a local variable by shading the instance variable. You can initialize the local array and memcpy its 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)); 
+5
source

Source: https://habr.com/ru/post/1386645/


All Articles