Using a protocol and a delegate - objective-c

I am trying to get some code in a view working. I have declared a delegate and it does not get instantiated, any Idea what I am missing?
I have tried to summarise how I have done this below. I think that the issue is that somewhere, my dataSource delegate needs to be instantiated.
I have a View called graph view and a delegate that is in the viewcontroller GraphViewController.
I know that the method in GraphView is doing something as it calls the AxisDrawing helper class and draws in Axes.
Here is the relevant code
In GraphView.h I set up the protocol and the dataSourceDelegate
#class GraphView;
#protocol GraphViewDataSourceDelegate
- (float)functionOfX:(float)xValue inGraphView:(GraphView *)sender;
#end
#interface GraphView : UIView
#property(nonatomic, weak) IBOutlet id <GraphViewDataSourceDelegate> dataSourceDelegate;
#end
Which I synthesize in GraphView.m
#import "GraphView.h"
#import "AxesDrawer.h"
#implementation GraphView
#synthesize dataSourceDelegate = _dataSourceDelegate;
Also in Graph View I try to use the delegate as follows (pixel is a CGPoint). This routine does run and I can draw to GraphView from here provided I do not try to use my protocol method. i.e. Some of my DrawRect stuff does get drawn which checks out the linking of the UIView to my custom View
pixel.y = [self.dataSourceDelegate functionOfX:pixel.x inGraphView:self];
++++Breakpoint put in here+++++
In GraphViewController I state that I implement the protocol and implement it as follows. The compiler warns me and spots when the implementation is done, turning of the warning. (I am only returning 3.0 at the moment as a test).
#interface
GraphViewController () <GraphViewDataSourceDelegate>
#property (nonatomic, weak) IBOutlet GraphView *graphView;
#end
...
-(float) functionOfX:(float)xValue inGraphView:(GraphView *)sender{
NSLog(#"fofx accessed");
return 3.0;
}
If I look at the GraphView* object just after a breakpoint, it seems to have no instance. What am I missing out.
This is from the trace at the breakpoint
_dataSourceDelegate struct objc_object * 0x0
EDIT: (In addition to #Clays answer below)
It turned out that my connection to the custom view was broke. This meant that the fault lay with the View not talking to the Custom ViewController. The link is made by ctrl dragging from the View Controller button in the Interface builder to the View within the ViewController.
This caused the ViewController to be instantiated and everything then worked fine.
To put it another way.
The link in question was the Outlet. This has to be declared in the ViewController as a property and then linked in IB using ctrl Drag from the ViewController Name-Bar to the View in the Controller.
Provided that you have added the Outlet property correctly, when you do the ctrl drag, your view will appear an option.
The context button popup information on the ViewController button in IB does give a clue.
If you have neglected to put the outlet property into the view controller, the link does appear in the context button popup but it is greyed out, and when you do the link your View is not named.
Once you put the outlet in, the name appears in the menu but not greyed out.

Make sure you've hooked everything up correctly: setting your GraphView's dataSourceDelegate, and your GraphViewController's graphView.
From the trace it looks like you haven't done that; or you lose the reference somewhere along the way because at some point nothing's holding on to it.

Related

Creating Delegate in UIScrollView Subclass

I have subclassed a UIScrollView to customize it a bit. I am trying to create a delegate that will notify several other classes that a user has done a certain thing in the UIScrollView. In my UIScrollView class I have the code below. The problem I am running into is I am getting the warning
Property 'delegate' 'retain (or strong)' attribute does not match the
property inherited from 'UIScrollView'
I see that this is because my Class in inheriting from UIScrollView, but my delegate is conforming to the NSObject. This is the first time I tried creating my own delegate. What can I do to fix this?
My Code:
#import <UIKit/UIKit.h>
#protocol ChangeSpaceDelegate <NSObject>
- (void)changeSpace:(int)spaceId;
#end
#interface CustomUIScrollView : UIScrollView {
id<ChangeSpaceDelegate> delegate;
}
#property (retain, nonatomic)id delegate;
#end
To answer your question specifically, you are redefining the property attribute on the delegate property you get from UIScrollView. It should, like all delegates, be weak (or, pre-iOS 5, unsafe_unretained).
However, you shouldn't do it this way. UIScrollView already has a delegate, and if you expect to put your own delegate object implementing your new delegate methods into it, the inner workings of UIScrollView aren't going to be happy. Define a new protocol and a new delegate property for it.
#property (weak, nonatomic) id<ChangeSpaceDelegate> changeSpaceDelegate;
You don't have to create the delegate object in custom scrollview class since you are subclassing it from UIScrollView. You can directly use it as self.delegate in your custom scrollview class.
As mentioned by #Steve Madsen, I often add own delegate properties for subclasses. Like UITableView has separate DataSource and Delegate properties, and being assigned with the same object. In a long run, this will definitely pay off by not forcing you to repeat what have been already implemented in super class, and keeping your subclass implementations more manageable

How to change the text of a textField from another view

I have this code:
ViewController .h
#property IBOutlet UITextField *field;
ViewController .m
#synthesize field;
ViewControllerTwo .h
#import "ViewController.h"
{
ViewController *ViewCont;
}
-(IBAction)changeTextField
ViewControllerTwo .m
#import "ViewController.h"
-(IBAction)changeTextField{
viewCont.field.text = #"hello";
}
The problem is that it doesn't work, although it doesn't give me any error. Does anyone know what I'm doing wrong?
Never modify another view controller's views. You are encountering one of many problems doing that. In your case, the likely cause is that the other view controller has not yet loaded its view, so all the IBOutlets are still nil.
You're breaking MVC, and that's going to cause lots of little problems like this. Instead of having ViewControllerTwo modify the outlets of ViewController, you should move the data (#"hello") into a model object that is shared by both view controllers. ViewControllerTwo would write to it, and ViewController would read from it. You can share that model object by passing it to the view controllers as a property, or by making the model a singleton.
You aren't instantiating your instance of class ViewController, so you are essentially sending a message to nil.

Modifying properties of a view controller form another view controller

In my project, there are two view controllers - let's say firstViewController and secondViewController. The second view controller has a button, and I want to make sure when the button gets pressed, the second view controller is telling somehow the first view controller - "hey, I got pressed, do something!", and it will do something, like changing a label. How is this possible to perform? Thanks in advance. Some code :
#interface firstViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *textLabel;
#end
#implementation firstViewController
#synthesize textLabel;
#end
#interface secondViewController : UIViewController
-(IBAction)buttonPressed;
#end
#implementation secondViewController : UIViewController
-(IBAction)buttonPressed{
// Hey, I got pressed! Set the text on textLabel to "OK"!
}
#end
This is a very simple case of delegation and protocol mechanism of objective-c..
have a look at this tutorial which will explain you how its done.. you can do this via notification also but that is not usually advised...(because notification is usually used when the receiver is unknown , like in the case of UIDeviceBatteryLevelDidChangeNotification you don't exactly know which view controller wants to know about this.)
I'd first consider what the button press means. Does it change the state of the model?
Say your model is an int, and the button increments it. The view controllers wouldn't message each other about that, they would just both observe the state of the model. (The one with the button could change the state, too).
Thinking about it this way, the solution probably isn't delegation. It's probably notification or KVO.
See the answer to this question: Passing data between two view controllers via a protocol
However, ask yourself if you really need a protocol here. If it is just between this classes or just about the question of accessing data of a class or sending information to a class then that is what the interface of a class is made for.
#interface firstViewController : UIViewController{
UILabel *textLabel; // I personally alway add IBOutlet here too, but I think that is not required.
}
#property (weak, nonatomic) IBOutlet UILabel *textLabel;
#end
And in SecondViewController.m:
#import "FirstViewController.h"
#implementation secondViewController : UIViewController
-(IBAction)buttonPressed{
// You will have to have a properly set instance variable firstViewController
[firstViewController.textLabel setText:#"OK"];
}
#end
So your second view controller needs to 'know' the first one. One way of achieving that is defining
FirstViewController *firstViewController;
as property and set it from wherever the second view controller is created and the first one is already known. How to do that exactly depends very much on the architecture of your app.

Get subView's containing view

If I have a view (mainView) in which I have added subViews. How do I get to subviews instance to mainView ?
I have a button in those subviews which when pressed should call a method in mainView, so I tried:
[myButton addTarget:self.presentingViewController
action:#selector(myMethod:)
forControlerEvents:UIControletcetc];
and
[myButton addTarget:self.parentViewController action:#selector....];
I read that parentViewController now returns nil in iOS 5, but presentingViewController doesn't seem the way to do it because its not presented modally. Its just a subview. Any hints?
Your question doesn't make it quite clear whether you are talking about views or view controllers. Use the superview property to access a view's parent.
There is generally no way to get from a view to its view controller.
It feels to me that you're trying to let your views know about objects beyond their scope.
If you need to notify about an event to anyone that included your view, you could use a delegate to do that.
Say:
#protocol YourClassDelegate
#optional
- (void)instanceOfYourClass:(YourClass *)instance tappedButton:(UIButton *)button;
#end
and then
#interface YourClass
#property (nonatomic, assign) id<YourClassDelegate> delegate;
#end
I hope you can take it from here, by synthesizing the property, assigning the delegate and calling the method when you need to.

When to alloc/init an ivar, and when not to

All,
In Apple's sample code "DateCell"
http://developer.apple.com/library/ios/#samplecode/DateCell/Introduction/Intro.html
the ivar "pickerView" is declared in MyTableViewController.h like this:
#interface MyTableViewController : UITableViewController
{
#private
UIDatePicker *pickerView;
UIBarButtonItem *doneButton; // this button appears only when the date picker is open
NSArray *dataArray;
NSDateFormatter *dateFormatter;
}
#property (nonatomic, retain) IBOutlet UIDatePicker *pickerView;
...
It is synthesized in the class file MyTableViewController.m like this:
#implementation MyTableViewController
#synthesize pickerView, doneButton, dataArray, dateFormatter;
...
When this app runs, I can insert NSLog(#"%#",pickerView) into ViewDidLoad and see that, sure enough, the ivar pickerView is real and has a value. Nowhere, though, does this class alloc/init pickerView. And that's the root of the question: how's it getting done if it's not being done explicitly?
Well, I naively copied this stuff to my code into my RootViewController.h and .m files figuring I could do the same, but pickerView stubbornly remains uninitialized (and my NSLog calls return "(nil)" as its value) no matter what I try short of explicitly alloc/initing it. Certainly RootViewController is being instantiated, or the RootView wouldn't be showing up, right? So shouldn't my pickerView be coming along for the ride just as it does for Apple?
So... do I have to manually alloc/init the pickerView instance variable? If so, where's Apple doing it? Or how are they doing it somehow otherwise?
I think I'm missing something very basic here, but I have no idea what it is. I can't see anything in Interface Builder or XCode that looks different between mine and theirs, but I've got tunnel vision at this point and can't see anything clearly anymore.
Thanks,
Bill
The IBOutlet modifier on this line is the key...
#property (nonatomic, retain) IBOutlet UIDatePicker *pickerView;
IBOutlet is a decorator that indicates that the object will be hooked up/connected/initialised when the corresponding xib (Interface Builder) file is loaded. The sample application you're looking up will contain a UITableViewController is a xib which has a connection to a UIPickerView.
You can either go the route of creating your own custom xib file and wire to an instance of UIPickerView or you can manually initialise the picker yourself.
Interface Builder (nib or xib) treats automatically IBOutlet ivar with connection of components.
IBOutlet is a special keyword that is
used only to tell Interface Builder to
treat an instance variable or property
as an outlet. It’s actually defined as
nothing so it has no effect at compile
time.
Your First iOS Application - The
View Controller Interface
Declaration, Making Connections
Interface Builder User Guide -
Defining Outlets and Actions in
Xcode