Objective C - How can i define a STATIC array of numbers accessible to all methods in my class?

StackOverflow https://stackoverflow.com/questions/3514478

  •  29-09-2019
  •  | 
  •  

Question

How can i define a STATIC array of numbers accessible to all methods in my class???

Was it helpful?

Solution

The same way you'd do it in C:

static int myArray[] = { 0, 1, 2, 3, 4, 5 };

If you want a static NSArray, you'll have to do some tricks. static isn't allowed for object types in Objective-C (since you can't declare an object directly - only pointers). In that case, you need to read up on Objective-C singletons. A quick way to implement it:

+ (NSArray *)myArray
{
  static NSArray *theArray;
  if (!theArray)
  {
    theArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:0], nil];
  }
  return theArray;
}

You can, of course, set it up to initialize with whatever kind of objects you'd like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top