Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Still confused by Objective C variable scope

Tags:

objective-c

I am trying to get some employee data from a JSON service. I am able to get the data and load it into an NSMutableArray, but I cannot access that array outside the scope of the method that gets the data.

TableViewController h filed

#import <UIKit/UIKit.h>
#import "employee.h"

@interface ViewController : UITableViewController

{
    //NSString *test;
    //NSMutableArray *employees;
}

@end

And here is my m file:

#define kBgQueue dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define scoularDirectoryURL [NSURL URLWithString: @"https://xxxx"]

#import "ViewController.h"

@interface ViewController()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    dispatch_async(kBgQueue, ^{

        NSData* data = [NSData dataWithContentsOfURL:
                        scoularDirectoryURL];

        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });
}


- (void)fetchedData:(NSData *)responseData {

    NSError* error;
    NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    NSMutableArray *employees = [[NSMutableArray alloc  ]init];
    if (!jsonArray) {

    } else {

        for (jsonObject in jsonArray){
            employee *thisEmployee  = [employee new];
            thisEmployee.fullName   = [jsonObject objectForKey:@"$13"];
            thisEmployee.state      = [jsonObject objectForKey:@"state"];
            thisEmployee.city       = [jsonObject objectForKey:@"city"];
            [employees addObject:thisEmployee];
        }
    }
}

Any help would be appreciated.

Bryan

like image 812
Bryan Schmiedeler Avatar asked May 11 '26 03:05

Bryan Schmiedeler


1 Answers

You were on the right track. All you have to do is uncomment the NSMutableArray declaration in your @interface, and then change this line:

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

to this

employees = [[NSMutableArray alloc] init];

Declaring the array in your interface will allow it to be accessed from anywhere within your implementation, or even from other classes and files if you declare it as a public property. When you make a declaration inside a function, that variables scope does not extend to outside of the function.

like image 50
Mick MacCallum Avatar answered May 12 '26 19:05

Mick MacCallum