PDA

View Full Version : Sharing methods between views




nathanlloyd
Mar 12, 2012, 10:52 AM
Hi guys, I've searched through the forums for an answer to this but can't find an answer that hits the nail on the head.

I started an app and added methods to my main UITableViewController but I'm now discovering that other UITableViewControllers could borrow the methods I added for the first.

What's the best way to share code amongst these? I'm guessing I need another file in my project, but I'm not sure what type of file this would be.

Any help would be appreciated.

Thanks.



ppilone
Mar 12, 2012, 11:01 AM
Without knowing the exact code you intend on sharing, the simplest solution would be to create a common UITableViewController subclass that contains the methods you wish to share. You should then inherit from that controller throughout your application where appropriate.

jonnymo5
Mar 12, 2012, 11:06 AM
You could also see if categories will work for your situation.

nathanlloyd
Mar 12, 2012, 11:06 AM
OK, so is that perfectly acceptable even though no UITableViewController will ever be attached directly to it?

Sorry just to explain a little more, the shared code is a method that extracts data from JSON and dumps it in a NSMutableArray that the Views then use.

dejo
Mar 12, 2012, 11:11 AM
Sorry just to explain a little more, the shared code is a method that extracts data from JSON and dumps it in a NSMutableArray that the Views then use.

This sounds like code that is better suited to being implemented in the Model part of your MVC design.

nathanlloyd
Mar 12, 2012, 11:14 AM
OK, I'll do some more research into MVC design.

Thanks for your help.

nathanlloyd
Mar 12, 2012, 11:41 AM
MVC - this is precisely what I need to implement so I can share code across my views.

My question is: When I'm adding my model files, what kind of files are they? I know that might not make sense, but for example when I'm adding class files, I make them of type NSObject. Do these files that hold my methods need to be of a particular type?

ppilone
Mar 12, 2012, 11:55 AM
In the simplest case your model is just a subclass of NSObject. There is no rule that dictates this (obviously wouldn't be a subclass of something like UIView) and it can depend on the framework you're using (e.g. CoreData models are subclasses of NSManagedObject).

In your case it sounds like a simple subclass of NSObject is all you need.

nathanlloyd
Mar 12, 2012, 11:56 AM
Cheers ppilone,

I'll try this tonight.

Thanks for everyone's input.