RGriffiths
RGriffiths

Reputation: 5970

Sharing a routine between view controllers

I have an app where I have a long routine to draw out a pdf document. I need to access this from a number of view controllers but I am not sure how. As the moment the code is copied into each of the VC's .m file which I know is ridiculous. One of the problems is that each VC has a large number of variables that need to be sent to the MakePdf routine and sending data between VCs appears to be problematic (or at least that is what I am beginning to understand).

Any pointers?

This is what I would like:

enter image description here

Upvotes: 1

Views: 74

Answers (3)

Geri Borbás
Geri Borbás

Reputation: 16608

I'd definietly create an abstract UIViewController class that holds the common characteristics, or a protocol at least, something like <PDFMakerDataSource>.

The PDFMaker singleton could be fine, define an activeViewController property on PDFMaker. So when the VC appears, I'd set that property, then you can call make on PDFMaker, that will use the currently bound VC as data source.


Anyway, why singletons? Why don't just create a PDFMaker object? You can create it with every VC, so every VC should have an instance of it.

Something like:

@interface PDFMaker : NSObject

+(id)pdfMakerWithDataSource:(id<PDFMakerDataSource>) dataSource;
-(void)makePDFwithCompletion:(void(^)(id PDF)) completionBlock;

@end

And the data source, like:

@protocol PDFMakerDataSource <NSObject>
@optional
-(NSString*)fileName;
-(UIImage*)coverImage;
-(NSString*)whateverData;
@end

So in every VC of the world can be now PDFMaker compilant, like:

@interface SomeViewController : UIViewController <PDFMakerDataSource>
@property (nonatomic, strong) PDFMaker *pdfMaker;
@end

@implementation SomeViewController

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.pdfMake = [PDFMaker pdfMakerWithDataSource:self];
}


// PDFMaker data source implementation (bind to UI for example)

-(NSString*)fileName
{ return self.fileNameTextField.text; }

-(NSString*)coverImage
{ return self.coverImageView.image; }

...

// Make That PDF

-(IBAction)makePDF
{
    [self.pdfMaker makePDFwithCompletion:^(id PDF)
    { NSLog(@"Shiny PDF just made: %@", PDF); }
}

@end

Upvotes: 1

GuybrushThreepwood
GuybrushThreepwood

Reputation: 5616

You could make all your view controllers that need access to this method (and any others) a subclass of a class which implements this function. They would then all inherit the make pdf code.

Upvotes: 3

David Ansermot
David Ansermot

Reputation: 6112

You should make a class, with a singleton methods (like "+sharedObject") with all the code. Then you access it with this code :

[[MyClass sharedObject] mySharedMethodForPdf];

http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/

Upvotes: 3

Related Questions