Search code examples
iosobjective-cafnetworkingviewcontrollernsobject

Best way to pass data between nsobject and a viewcontroller


I have an helper class which has a function that makes an api call and get some json data and formats and returns an array. My TableViewController is trying to access that returned array. Yes, as you expected my tableviewcontroller viewDidLoad method is not able to access the array object returned by my helper class.

@interface MyHelperClass : NSObject

@property (nonatomic,retain)NSArray *myArray;

@end

@implementation MyHelperClass

@synthesize myArray;

- (NSArray *) returnArray{

 // make api calls and return array

  return myArray;

}

@end

@implementation MyTableViewController
{
- (void)viewDidLoad
{
    [super viewDidLoad];

    MyHelperClass *myhelper = [[MyHelperClass alloc]initWithPath:getSpacePath];

    allTopics = (NSArray *)[myhelper returnArray];

    NSLog(@"Load my Array%@",allTopics);
}
}

My question is, do I need to implement a delegate to pass the data around or is there any other way to pass around the data to my view controller?

P.S : I do not want to use global variable


Solution

  • Sorry for posting the answer so late. I figured out what the problem is. As @A-Live mentioned, the Rest API calls using AFNetworking is using async calls and hence it's not returning the array to the main thread within it's execution time. In my case,

    -(void)viewDidLoad {
    
    NSLog(@"I get called first");
    
    MyHelper *helper = [[MyHelper alloc]init];
    
    // returns array. However, [helper getData] is an async call under the hood. Hence myArray is nil
    myArray = [helper getData];
    
    }
    

    To solve this problem, I took advantage of NSNotification.

    @implementation MyHelper{
    
       -(NSArray *)getData(){
    
        [[NSNotificationCenter defaultCenter] postNotificationName:@"some.name.notification" object:JSON];
    
        }
    }
    
    -(void)viewDidLoad(){
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData:) name:@"some.name.notification" object:nil];
    
    }
    
    -(void)loadData:(NSNotification *)notif {
    
    // You can access the JSON object passed by the helper in here
    
    NSArray *myArray = [notif object];
    
    // do whatever you want with the array.
    
    }
    

    I hope I am detailed enough. I hope this helps someone and saves a lot of headache.