objective-c - 仍然对 Objective C 变量作用域感到困惑

标签 objective-c

我正在尝试从 JSON 服务获取一些员工数据。我能够获取数据并将其加载到 NSMutableArray 中,但我无法在获取数据的方法范围之外访问该数组。

TableViewController h 提交

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

@interface ViewController : UITableViewController

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

@end

这是我的 m 文件:

#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];
        }
    }
}

如有任何帮助,我们将不胜感激。

布莱恩

最佳答案

你走在正确的道路上。您所要做的就是取消注释 @interface 中的 NSMutableArray 声明,然后更改此行:

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

到此

employees = [[NSMutableArray alloc] init];

在接口(interface)中声明数组将允许从实现中的任何位置访问它,如果将其声明为公共(public)属性,甚至可以从其他类和文件访问它。当您在函数内部进行声明时,该变量的作用域不会扩展到函数外部。

关于objective-c - 仍然对 Objective C 变量作用域感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20011794/

相关文章:

iOS13系统UITabBar

ios - 另一个 View Controller 上的 UIAlertView 崩溃问题

ios - 桥接 swift 和 objective-c

objective-c - 使用 NSURLSession 时 UI 被阻塞

具有非零 `contents` 的 QTMovieLayer 的 iOS 替代品?

ios - 从 `UIView` 获取类的实例

objective-c - 在 block 内使用 self 的方法

ios - 在选择器中为 scheduleTimerwithTimeInterval 传递参数

ios - 计算数组中的平均值

iOS正确比较文件路径