I have 2 classes. A and B. Inside ClassA I have a method which retrieve JSON data and adds into an array. I want to access this array from ClassB. How can I achieve it?
ClassA.h
- (void)viewDidLoad
{
//initialise arrayPlaces and arrayWeather
[super viewDidLoad];
dispatch_async(queue, ^{
NSData* data = [NSData dataWithContentsOfURL:
serverURL];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError *error;
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
tempArray = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
//declare arrayPlaces
arrayToPass = [[NSMutableArray alloc] init];
//...codes to add array here using a loop...
[arrayToPass addObject:tempString];
}
In ClassB, I have a tableView which i want to get all the array from ClassA. How can I achieve this?
ClassA *cA = [[ClassA alloc]init];
ClassA.view;
arrayReceived = ClassA.arrayToPass;
The above doesn’t seem to work when implemented in ClassB.
ClassB *cB = [[ClassB alloc] init];
[cB setArrayReceived:arrayToPass];
Neither does this work when implemented in ClassA after this portion of the code.
“//…codes to add array here using a loop…
[arrayToPass addObject:tempString];
Please help!! Thanks!
The reason your code does not work is because
fetchData:is done asynchronously andarrayToPassis still not populated when the codearrayReceived = ClassA.arrayToPass;runs.So we have to let
ClassBknow about that.How about first declaring a protocol
ClassADelegatebetweenClassAandClassB, and declare a property inClassAthat of typeClassADelegatelike this:then make
ClassBa delegate of thisand of course implement the method
classADidReceiveData:in ClassB:Then modify
fetchData:like:So that when
ClassAreceived data, it can makeClassBnoticed about that.The overall usage is:
If you have something to be done after fetching data in
ClassB, then do it inclassADidReceiveDatainClassB.