Issue getting delegate/protocol to work correctly - ios

I am trying to create a way to pass data from Controller A (CDCFaderController) to Controller B (CDCSendsViewController) this is because although Controller A owns a view, I need to send some of that views data to Controller B as it has some additional functionality I want to access.
My logic was to setup the delegate in Controller A and receive it in Controller B for use.
Currently I have this as a test to get it working:
Controller A .h
#protocol CDCSendsControllerDelegate <NSObject>
-(void)test:(NSString*)str;
#end
#interface CDCFaderController : UIViewController
<UIScrollViewDelegate, CDCControlDelegate, CDCFadersSideBarDelegate>
#property (nonatomic, weak) id <CDCSendsControllerDelegate> delegate; // delegate synthesis
Controller A .m
-(void)delegateTest {
[self.delegate test:#"Hello world!"];
}
And in the receiving Controller B:
Controller B .h
#interface CDCSendsViewController : UIViewController
<CDCControlDelegate, CDCSendsControllerDelegate>
Controller B .m
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"VDL CALLED");
CDCFaderController * faderController = [[CDCFaderController alloc] init];
faderController.delegate = self;
}
-(void) test:(NSString*)str{
NSLog(#"%#", str);
}
The idea i thought was that when i loaded Controller B it would pull through the print from Controller A and display the information?
In practice controller B wont be instantiated by the view as Controller A is the owner of the view. So I was wondering how to get B to call and pull data from A correctly to get this working? B is more of a background controller adding support functionality to A by using some of its passed data.
Hope this helps I can provide any further detail

I saw the above code. Actually your CDCFaderController is locally initialised in viewDidLoad method. ARC will release that controller object after viewDidLoad is executed as it is no longer used anywhere which will make the delegate nil as well.
Kindly make a property of CDCFaderController and initialise it. After that it should work fine.

Related

Setting the delegate from third to first viewController

I have three viewControllers. When I'm on the third view controller I want to send a message to the first one. I'm using a protocol and trying to set the delegate for this.
viewControllerC.h
#protocol ViewControllerCDelegate
- (void)performAction;
#end
...
#property (nonatomic, strong) id<ViewControllerCDelegate> delegate;
viewControllerA.h
#interface ViewControllerA : UIViewController <ViewControllerCDelegate>
viewControllerA.m
...
- (void)performAction {
NSLog(#"Action was performed");
}
So the only problem is, I can't set the delegate from the third to the first. How can I set viewControllerC's delegate to viewControlerA?
Here's an image to describe it:
You'd have to pass along the A controller through to the B controller to be set as the delegate for C when it is created. Kind of messy.
In this case though it might make more sense to use a notification model where Controller A listens for a NSNotification that the action was completed on C.

Where to set delegate = self? Or should I just use a different design pattern?

EDIT: edited for clarity
Disclaimer: I'm new and pretty bad. But I have tried very hard and read lots of stuff to figure this out, but I have not...
I think my whole delegate pattern would work, except I can't figure out how to set the delegate property of ViewController to self in the MatchLetter class. The reason is because I can't figure out how to call code there. It's not a view controller, so viewDidLoad or prepareForSegue won't work.
This is what I've got:
ViewController.h
#import <UIKit/UIKit.h>
#class ViewController;
#protocol letterMatchProtocol <NSObject>
- (BOOL) isLetterMatch:(char) firstLetter;
#end
#interface ViewController : UIViewController
#property (nonatomic, weak) id <letterMatchProtocol> delegate;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
char c = 'a';
// This is the method I want to delegate to MatchLetter, to have a BOOL returned
BOOL returnValue = [self.delegate isLetterMatch:c];
}
#end
MatchLetter.h
#import <Foundation/Foundation.h>
#import "ViewController.h"
#interface Delegate : NSObject <letterMatchProtocol>
#end
MatchLetter.m
#import "MatchLetter.h"
#implementation Delegate
// this is the code I think I need to run here, to set the delegate property...
// ViewController *viewController = [ViewController new];
// viewController.delegate = self;
// ... so that isLetterMatch can be run here from ViewController.m
// But I don't know where to put this code, or how to get it to run before the ViewController
// especially since there are no segues or views to load.
- (BOOL) isLetterMatch:(char)firstLetter {
if (firstLetter == 'a') {
return YES;
}
else {
return NO;
}
}
#end
Can somebody please tell me the best way to proceed? Thanks for reading
You asked "Where to set delegate = self? Or should I just use a different design pattern?".
Answer: Don't. An object should never be it's own delegate.
Your code is quite a mess.
Don't name a class "Delegate". A delegate is a design pattern. The whole point of a delegate is that any object that conforms to a particular protocol ("speaks the language") can serve as the delegate. You don't need to know what class of object is serving as the delegate, but only that it speaks the language you need.
An analogy: When you call the operator, you don't care who is working the operator desk. You don't care about his/her gender, religion, ethnic background, how tall they are, etc. You just care that they speak your language.
Likewise, when you set up a delegate, it doesn't matter what type of object gets set as the delegate. All that matters is that the object that is the delegate conforms to the protocol for that delegate.
A table view can have ANY object serve as it's delegate, as long as that object conforms to the UITableViewDelegate protocol. You usually make you view controller be the table view's delegate, but you don't have to. You could create a custom class that manages your table views, and have it be the delegate. There is no "TableViewDelegate" object class. There is instead a UITableViewDelegate protocol, and any object that conforms to the protocol can act as a table view's delegate.
Edit: Your question is confusing. I think what you're proposing is that your Delegate class would create a view controller and make itself the delegate for the view controller.
If that's what you are talking about, your thinking is backwards. The view controller is using the Delegate class as a helper class. Any given instance of a view controller class can create an instance of the Delegate class and set it as it's delegate if it desires. You might have 3 instances of ViewController at one time, each with it's own instance of your Delegate class.
Thus, the ViewController object is the one that should create and set up an instance of Delegate if it needs one:
- (void) viewDidLoad;
{
self.delegate = [[Delegate alloc] init];
//other setup here
}

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:
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/
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.
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

Sending data from a viewcontroller to another

I am struggling to make a simple thing (at least I think it's simple) but I just can't do it!
I will try to explain a little bit.
It's an app which displays information. When the user is inside a view, he can click on a button, which displays a popoverview, where he can choose which information he wants to know.
Actually, I can't create an action that changes the UILabel text I created in the main view when the user clicks on the popoverview's buttons.
Anyone has any idea?
Just for you to know: the main view I created a class for it, and also for the popoverview. Although, the popover view I created its design in a XIB file (I don't know if this is important, that's why I am putting this).
Well, I hope you guys were able to understand my question.
Thanks in advance.
Fernando.
Just create a property from the viewcontroller and access it from the consumer (other viewcontroller )
You will have to use delegation in order to see changes in the main view when you are making different actions inside the popover. First, you need to create a protocol inside your popover controller header file:
#import <Foundation/Foundation.h>
#class MyPopoverController;
#protocol MyPopoverDelegate
- (void)valueChanged:(NSString*) newVal;
#end
#interface MyPopoverController: UIPopoverController
#property (weak) id<MyPopoverDelegate> delegate;
#end
Then in .m you implement it like this:
- (void) someActionOccured
{
if([self.delegate respondsToSelector:#selector(valueChanged:)]){
[self.delegate valueChanged:valueYouWantToSendBack];
}
}
Remember that in your main class you have to implement MyPopoverDelegate protocol:
#interface MainViewController: UIViewController <MyPopoverDelegate>
And when you instantiate your popover controller:
/*
** inside MainViewController.m
*/
// remember to assign it's delegate
MyPopoverController *popoverController = [MyPopoverController alloc] init];
popoverController.delegate = self;
Also, you'll have to implement the protocol's method:
/*
** inside MainViewController.m
*/
- (void)valueChanged:(NSString*) newVal
{
// process the string and display it where you need it
}

Unable to set custom protocol delegate using ARC with two UITableViewControllers using UINavigationController

I'm trying to set the delegate for my custom protocol that has one required method allowing me to pass an array of objects back in the hierarchy of two UITableViewControllers. My delegate continues to return nil. Due to this, my required method is never called.
I'm wondering if the datasource and delegate implementations with my UITableViewControllers is causing a conflict. Also, perhaps ARC is getting in the way when declaring the delegate?
It should be noted that both UITableViewControllers were built using Storyboard and are navigated using segues within a UINavigationController (not sure if this may be causing issues or not).
The nav is --> AlarmViewController --> AlarmDetailsViewController. I create an Alarm object in my AlarmDetailsViewController that contains all the details for an alarm, place it into an array and I want to pass that array back to my AlarmViewController to be displayed in a custom cell in the table.
NOTE: I want to use the Delegate pattern here. I'm not interested in solutions that invoke NSNotifications or use my AppDelegate class.
AlarmDetailsViewController.h
#import "Alarm.h"
#protocol PassAlarmArray <NSObject>
#required
-(void) passAlarmsArray:(NSMutableArray *)theAlarmsArray;
#end
#interface AlarmDetailsViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
//.....
id <PassAlarmArray> passAlarmsArrayDelegate;
}
#property (nonatomic, retain) id <PassAlarmArray> passAlarmsArrayDelegate;
#end
AlarmDetailsViewController.m
#import "AlarmDetailsViewController.h"
#interface AlarmDetailsViewController ()
#end
#implementation AlarmDetailsViewController
#synthesize passAlarmsArrayDelegate;
-(void) viewWillDisappear:(BOOL)animated
{
NSLog(#"delegate = %#", self.passAlarmsArrayDelegate); // This prints nil
[[self passAlarmsArrayDelegate] passAlarmsArray:alarmsArray];
}
//....
#end
AlarmViewController.h
#interface AlarmViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate, PassAlarmArray>
{
//...
AlarmDetailsViewController *alarmDetailsViewController;
}
#property (nonatomic, retain) AlarmDetailsViewController *alarmDetailsViewController;
#end
AlarmViewController.m
#import "AlarmViewController.h"
#import "AlarmDetailsViewController.h"
#import "AlarmTableViewCell.h"
#import "Alarm.h"
#interface AlarmViewController ()
#end
#implementation AlarmViewController
#synthesize alarmDetailsViewController;
- (void)viewDidLoad
{
[super viewDidLoad];
// This is where I'm attempting to set the delegate
alarmDetailsViewController = [[AlarmDetailsViewController alloc]init];
[alarmDetailsViewController setPassAlarmsArrayDelegate:self];
}
//....
//My #required protocol method which never gets called since my delegate is nil
-(void) passAlarmsArray:(NSMutableArray *)theAlarmsArray
{
alarmsTableArray = theAlarmsArray;
NSLog(#"alarmsTableArray contains: %#", alarmsTableArray); // Never gets called due to delegate being nil
NSLog(#"theAlarmsArray contains: %#", theAlarmsArray); // Never gets called due to delegate being nil
}
#end
I've attempted to set the delegate in a method that fires when a button is pressed in AlarmViewController (as opposed to the viewDidLoad method) but that does not work either.
I'm assuming I've got a logic flow error somewhere here . . . but nearly 2 days of hunting and rebuilds haven't uncovered it. Ugh.
You're setting your delegate in the wrong place, and on a different instance of the controller than the one you will get when you do the segue. You should set the delegate in the prepareForSegue method if you're pushing AlarmDetailsViewController from AlarmViewController
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
AlarmDetailsViewController *alarm = segue.destinationViewController;
alarm.passAlarmsArrayDelegate = self;
}
You really need to understand the life cycle of view controllers, how and when they're instantiated, and when they go away. This is the very heart of iOS programming, and Apple has extensive documentation on it. Reading up on segues would also be very useful. A segue (other then an unwind segue) always instantiates a new instance of the destination controller. So, when your segue is performed, whether directly from a button, or in code, a new (different from the one you alloc init'd directly) details controller is instantiated. Before that segue is performed, prepareForSegue: is called, and that's when you have access to the one about to be created. That's the place to set a delegate or pass any information on to the destination view controller.
Did you try replace (nonatomic, retain) with (nonatomic, strong) since you are using ARC?
Auto-synthesized properties like your alarmDetailsViewController property have backing ivars prefixed with underscores, e.g. _alarmDetailsViewController. Your alarmDetailsViewController ivar (the alarmDetailsViewController declared inside the #interface ... {} block in AlarmViewController.h) is different from the backing ivar of your alarmDetailsViewController property.
Just delete your alarmDetailsViewController ivar and use the #property, preferably through self.alarmDetailsViewController.

Resources