Search code examples
objective-cioscocoa-touchnsmutablearraynsarray

addObjectsFromArray: not copying into global NSMutableArray


So here is a partial sample of the relevant code.

static NSMutableArray *radioInputArray;
static NSMutableArray *buttonsArray;


- (IBAction)lookForRadioButtons:(id)sender {
    //  NSLog(@"Testing");
    NSError *error;
    NSString *radiostr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"getRadios" ofType:@"txt"] encoding:NSASCIIStringEncoding error: &error] ;
    if (radiostr == nil)
    {
        NSLog (@"Error! %@", error);
    }
    else
    {
        NSLog(@"%@",radiostr);
        NSString *radiotxt=  [webView stringByEvaluatingJavaScriptFromString:radiostr];
        NSLog(@"%@", radiotxt);
        NSArray *myRadios = [radiotxt componentsSeparatedByString:@"::"];
        [radioInputArray addObjectsFromArray:myRadios];
        NSLog(@"%d", myRadios.count);
        NSLog(@"Number of buttons in global radio array %d", radioInputArray.count);
        NSLog(@"%d", scrollViewer.subviews.count);
    }
}

So it throws no exceptions and seems to work properly except after addObjectsFromArray:, my count in the global NSMutableArray is 0 (the count in the myRadios = 56). I am pretty sure they should be equal at this point but are not. I have declared my NSMutableArray up near the top so that it can be globally accessed. Am I missing something such as allocating and initializing this? Does it not do that automatically like in C#? Again, this is my first foray into the Objective-C world from Windows programming so please be gentle yet feel free to be critical.


Solution

  • Your two global arrays are not initialized.

    The lines

    static NSMutableArray *radioInputArray;
    static NSMutableArray *buttonsArray;
    

    just define the two variables as pointers to NSMutableArray, so you need to get them to point at an actual instance of the class NSMutableArray.

    Somewhere in your initialization code, or through an accessor (best if a class method), you should set the variables to an empty, newly allocated NSMutableArray.

    Here is a way to do it:

    + (NSMutableArray*)radioInputArray
    {
        if (!radioInputArray) {
            radioInputArray = [[NSMutableArray alloc] init]; 
        }
    
        return radioInputArray;
    }
    

    Then use the accessor in your code instead of the global variable.