简体   繁体   中英

Objective-C – Sending data from NSObject subclass to an UIViewController

I have an UIViewController which has a UITableView inside. In this view controller I want to display some data that I have downloaded from the internet. So for this I have created a helper class called OfficesParser which is supposed to do the following:

  1. Download the data from the internet with ASIHTTPRequest
  2. Process the data with a JSON parser
  3. When finished, send the data back to my view controller

In my view controller I'm alloc ing and init ing my helper class in -viewDidLoad like so:

self.officesParser = [[[OfficesParser alloc] init] autorelease]; //officesParser is a retained property

Then in -viewWillAppear: I call the the method for the officesParser object that will start the download process like so:

[self.officesParser download];

In my helper class OfficesParser ASIHTTPRequest has a delegate method that tells you when a queue has finished downloading. So from this method I want send the data to my view controller. I would think this would work, but it didn't:

- (void)queueFinished:(ASINetworkQueue *)queue {

    NSArray *offices = [self offices];
    OfficesViewController *ovc = [[OfficesViewController alloc] init];
    [ovc setOffices:offices];

}

With this code in mind, how would you achieve what I'm trying to do with proper code?

You need to take a look at delegates and protocols . They're exactly what you're looking for, as they let classes communicate without having to persist a reference. Here is another explanation on them.

Your code:

OfficesViewController *ovc = [[OfficesViewController alloc] init];

Creates new instance property of OfficesViewController . Since it's a new instance it does not have a connection to the OfficesViewController you triggered after downloading and parsing process. To be able to comunicate b/w OfficesViewController and OfficesParser create a modified init method for OfficesParser that allows week pointer to the OfficesViewController .

@interface OfficesParser ()

@property(nonatomic,assign)OfficesViewController *ovc;

@end

@implementation OfficesParser

@synthesize ovc;

-(id)initWithDelegate:(OfficesViewController*)delegate{
    ovc = delegate;
    return [self init];
}

Now you can access your ovc delegate.

- (void)queueFinished:(ASINetworkQueue *)queue {
    NSArray *offices = [self offices];
    [ovc setOffices:offices];
}

Finally create your OfficesParser like that

self.officesParser = [[OfficesParser alloc] initWithDelegate: self];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM