Tutorial :Whats the best place to set a View Controller ivar?



Question:

I have an XML reader class which I initialize with a URL

- (id)initWithURL:(NSURL *)url  

This class adds objects to an array in the calling class using an instance variable

// in the interface  ViewController *viewController;  // in the implementation  [viewController addObject:theObject];  

Now, I initialize my XML reader class, then set the View Controller separately:

XMLController *xmlController = [[XMLController alloc]                      initWithURL:url];  xmlController.viewController = self;  

My question is whether I should create a new init function which sets the viewController at the same time. Thanks.

Edit: I forgot to add that my XML reader starts downloading and parsing the class in the init function.


Solution:1

If your init routine is going to cause delegate/controller calls, or set off asyncronous activities (potentially including your downloading) that could message the delegate, then you should include it in the init function.

Otherwise your controller might miss potential delegate messages such as xmlController:didStartConnection that might be called before your initWithURL routine returns.

Also, if the controller/delegate is a required part of the XMLController activities, then you should include it in your init routine.

So yes, in this case I would suggest:

XMLController *xmlController = [[XMLController alloc] initWithURL:url andController:self];  


Solution:2

It's entirely up to you. You can see examples of both styles all over Apple's code.

As long as you don't make any assumption about the viewController property's value being constant over time, it should be fine to leave it as-is.

BTW, you might think about refactoring the addObject: logic into a protocol instead of requiring a specific subclass. Something like:

-xmlController:didDecodeObject:  

Or whatever makes sense for your XMLController object's logic.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »