views:

65

answers:

2

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.

+4  A: 

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.

Andrew Pouliot
+2  A: 

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];
Peter N Lewis