fewaf
fewaf

Reputation: 151

How to create an array outside of a function, and be able to add to it in other functions

It seems if I do something like:

NSMutableArray *randomSelection = [[NSMutableArray alloc] init];

Then this needs to be in a function, and I can't modify it later using a different function.

I tried just instantiating it in the .h file,

@interface ViewController:
{
  NSMutableArray *Values;
}

But then when I try to append to it during runtime, nothing happens. I try to append to it with this:

int intRSSI = [RSSI intValue];
NSString* myRSSI = [@(intRSSI) stringValue];
[Values addObject:myRSSI];

But the array remains empty when I do this.

How can I fix this?

Upvotes: -1

Views: 55

Answers (1)

ppalancica
ppalancica

Reputation: 4277

The recommended way is to create a property;

// ViewController.h

@interface ViewController : UIViewController
{
}

@property (nonatomic, strong) NSMutableArray *values;

@end

Then override the getter for that property, to lazy-initialize it, i.e. the array will be allocated and initialized on first call of the NSMutableArray property's getter:

// ViewController.m

@interface ViewController ()

@end

@implementation ViewController

- (NSMutableArray *)values
{
  if (!_values) {
    _values = [[NSMutableArray alloc] init];
  }

  return _values;
}

- (void)viewDidLoad
{
  [super viewDidLoad];

  //int intRSSI = [RSSI intValue];
  //NSString *myRSSI = [@(intRSSI) stringValue];
  //[self.values addObject:myRSSI];
  // Keep it simple:
  [self.values addObject:RSSI];
}

@end

Upvotes: 1

Related Questions