开发者

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

I have an UIViewController which has a UITableView inside. In this view controller开发者_如何学Go 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 allocing and initing 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜