我正在尝试从JSON服务获取一些员工数据。我能够获取数据并将其加载到NSMutableArray中,但是我无法在获取数据的方法范围之外访问该数组。
TableViewController已提交
#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];
}
}
}
任何帮助都将不胜感激。
布赖恩
答案 0 :(得分:10)
你走在正确的轨道上。您所要做的就是取消注释@interface中的NSMutableArray声明,然后更改此行:
NSMutableArray *employees = [[NSMutableArray alloc] init];
到这个
employees = [[NSMutableArray alloc] init];
在您的界面中声明数组将允许从您的实现中的任何位置访问它,或者如果您将其声明为公共属性,则可以从其他类和文件访问它。在函数内部进行声明时,变量作用域不会扩展到函数外部。
答案 1 :(得分:4)
只是详细说明变量的范围,你有几种方法来声明它们。最常用的是:
@interface MyObject : NSObject { //this can be any class NSString *instanceVariable; } @implementation MyObject -(void)someStrangeMethod { instanceVariable = @"I'm used here"; NSLog(@"%@",instanceVariable); } //from subclasses @interface MySubclassObject: MyObject { //see that the variable is not declared here; } @implementation MySubclassObject -(void)anotherStrangeMethod { [super someStrangeMethod]; // this will print the value "I'm used here" instanceVariable = @"I'm changing my value here"; //here we access the variable; }
@private
标记之后声明它。你也有@protected
标签,虽然没用过多。如果您想拥有一个可以在类外部访问的变量,请在界面中将其声明为属性。
此外,您可以使用@private
将属性设为私有,但这与属性的目的相矛盾。