Trying to Implement Delegate Inheritance - iphone

I have a class called ToolbarView which is a subclass of UIView and basically creates a UIView that has a disappearing / reappearing UIToolbar on top. I also have a subclass of ToolbarView called DraggableToolbarView enables the user to drag the view around the screen.
I need to create a delegate for ToolbarView so it can notify another object / class of when the toolbar reappears and disappears. I also need to create a delegate for DraggableToolbarView so I can notify another object / class when the view is dragged. DraggableToolbarViews delegate will also need to notify another object / class of when the toolbar reappears and disappears.
So I decided to implement ToolbarViewDelegate, and have DraggableToolbarViewDelegate inherit from it and have its own method like following:
ToolbarView.h
#import <UIKit/UIKit.h>
#protocol ToolbarViewDelegate;
#interface ToolbarView : UIView <UIGestureRecognizerDelegate>
{
id <ToolbarViewDelegate> _toolbarViewDelegate;
}
#property(nonatomic, assign) id <ToolbarViewDelegate> toolbarViewDelegate;
#end
ToolbarView.m
#import "ToolbarView.h"
#import "ToolbarViewDelegate.h"
...
- (void) showBars
{
...
if (self.toolbarViewDelegate)
{
[self.toolbarViewDelegate toolbarViewWillShowToolbar:self];
}
...
}
- (void) hideBars
{
...
if (self.toolbarViewDelegate)
{
[self.toolbarViewDelegate toolbarViewWillHideToolbar:self];
}
...
}
ToolbarViewDelegate.h
#class ToolbarView;
#protocol ToolbarViewDelegate
#required
- (void) toolBarViewWillShowToolbar:(ToolbarView *)toolbarView;
- (void) toolBarViewWillHideToolbar:(ToolbarView *)toolbarView;
#end
DraggableToolbarView.h
#import "ToolbarView.h"
#protocol DraggableToolbarViewDelegate;
#interface DraggableToolbarView : ToolbarView
{
id <DraggableToolbarViewDelegate> _draggableToolbarViewDelegate;
}
#property(nonatomic, assign) id <DraggableToolbarViewDelegate> draggableToolbarViewDelegate;
#end
DraggableToolbarView.m
#import "DraggableToolbarView.h"
#import "DraggableToolbarViewDelegate.h"
...
- (void)drag:(UIPanGestureRecognizer *)sender
{
...
if (self.draggableToolbarViewDelegate)
{
[self.draggableToolbarViewDelegate draggableToolbarViewWillDrag:self];
}
...
}
...
DraggableToolbarViewDelegate.h
#import "ToolbarViewDelegate.h"
#class DraggableToolbarView;
#protocol DraggableToolbarViewDelegate <ToolbarViewDelegate>
#required
- (void) draggableToolbarViewWillDrag:(DraggableToolbarView *)draggableToolbarView;
#end
SomeViewController.h
#import <UIKit/UIKit.h>
#import "ToolbarViewDelegate.h"
#import "DraggableToolbarViewDelegate.h"
#interface SomeViewController : UIViewController <ToolbarViewDelegate, DraggableToolbarViewDelegate>
{
}
#end
SomeViewController.m
#import "DraggableToolbarView.h"
...
- (void) toolbarViewWillShowToolbar:(ToolbarView*)toolbarView
{
//NSLog(#"Toolbar Showed");
}
- (void) toolbarViewWillHideToolbar:(ToolbarView*)toolbarView
{
//NSLog(#"Toolbar Hidden");
}
- (void) draggableToolbarViewWillDrag:(DraggableToolbarView*)draggableToolbarView
{
//NSLog(#"Dragged");
}
...
[draggableToolbarView setDraggableToolbarViewDelegate:self];
...
When I do this only the DraggableToolbarDelegate methods are responding. However when I also do [drabbleToolbarView setToolbarViewDelegate:self] it works. I've tried doing each delegate separately without inheritence and it works fine so I believe the problem isn't in any other part of the code.
Anyone might know why? I figured by making the protocols inherit, I wouldn't also have to set the ToolbarViewDelegate for a DraggableToolbar object.
UPDATE: Added a lot more code

In your code, any given DraggableToolbarView instance has two properties to connect to delegates, one called toolbarViewDelegate which it inherits from its superclass, and one called draggableToolbarViewDelegate which is defined in DraggableToolbarView itself. You've got to set both of those if you want the controller to get all the delegate messages.
What you're trying to do is possible, however. You need to use the same property name in both your view classes, so that there is only one delegate connection for any instance.
First, change the name of the delegate in the superclass. (Note that you don't need, and indeed shouldn't bother, to declare an ivar for the property -- it's created by #synthesize.)
#interface ToolbarView : UIView <UIGestureRecognizerDelegate>
#property (nonatomic, assign) id <ToolbarViewDelegate> delegate;
#end
You will use the same property name in the subclass.
#interface DraggableToolbarView : ToolbarView
#property (nonatomic, assign) id <DraggableToolbarViewDelegate> delegate;
#end
This is allowed as long as the name of the backing ivar in the subclass is different than that of the superclass, e.g.,
// In superclass
#synthesize delegate;
// In subclass
#synthesize delegate = delegate_;
Now change all the delegate messages in the two view classes to use this one property:
- (void)showBars
{
if (self.delegate)
{
[self.delegate ...
- (void)drag:(UIPanGestureRecognizer *)sender
{
//...
if (self.delegate)
{
[self.delegate ...
Now you can send setDelegate: to a DraggableToolbarView and it will use the same delegate for the dragging methods and the show/hide methods.
Finally, a terminology/explanatory note. In response to your previous question, Caleb used the correct term for "stacked" protocols, and Richard did not. Protocols don't inherit from each other, but one protocol can adopt the other. The relationship is similar, but distinct. When an object conforms to a protocol, it promises to implement the methods declared in that protocol. No implementation comes along with the protocol. The same is true of one protocol adopting the other -- the methods are just declared to exist in both. When you write:
#protocol DraggableToolbarViewDelegate <ToolbarViewDelegate>
you are saying that any object which promises to implement DraggableToolbarViewDelegate's methods will also implement the methods from ToolbarViewDelegate. That's all that it means. Again, no implementation comes along with that promise.
In this case, that means that a DraggableToolbarView can expect its delegate to implement the methods in ToolbarViewDelegate.

You have not given the entire code, but from whatever is out here,
Make sure that
Your ToolBarView and its subclasses have an id <ToolBarViewDelegate> delegate as a property.
Your DraggableToolbarViewDelegate extends NSObject protocol.
and your other ViewController object conforms to delegate protocol and not the toolbarview.
Once your controller gives implementation of delegates methods and conforms to the protocol, set the delegate of view's object to self and then use delegate property set in the view to call these protocol methods.

Related

Access delegate methods of UIPageViewController when you've created a protocol

I'm using the UIPageViewController and I've made my own protocol like this:
#protocol MyDataDelegate <NSObject, UIPageViewControllerDelegate>
- (void)recieveData:(NSString *)theData;
#end
How can I set the delegate of UIPageViewController to self so I can use those delegate methods? The normal code for this would be self.delegate = self; but since I've made another delegate it gives me a warning "Assigning to 'id<MyDataDelegate>' from incompatible type 'PageScrollViewController *const_strong'" I want to set this to self so I can access the delegate methods of the UIPageViewController
Your subclass eclipses delegate property of UIPageViewController. Give your delegate property some other name, for instance: #property (nonatomic,weak) id myDelegate;
Have you declared your PageScrollViewController class to conform to MyDataDelegate? You can either do this in the main #interface declaration:
#interface PageScrollViewController : UIPageViewController <MyDataDelegate>
// ...
#end
Or in the class category in your .m file:
#interface PageScrollViewController () <MyDataDelegate>
// ...
#end

How to use #protocol in AppDelegate iPhone app?

I am working in iPhone app with 5 screens. I want to refresh the values in the screen 4th in UITabBarController. I have added #protocol in AppDelegate but it is not calling. This is the first time am using #protocol could you please help me to solve this issue,
In AppDelegate.h
#protocol ReloadViewControllerDelegate <NSObject>
-(void) refreshViewController:(NSString *)result;
#end
id refreshViewControllerDelegate;
#property (nonatomic, retain) id refreshViewControllerDelegate;
and i have synthesized.
In AppDelegare.m
#synthesize refreshViewControllerDelegate;
if ([refreshViewControllerDelegate conformsToProtocol:#protocol(ReloadViewControllerDelegate)])
{
[refreshViewControllerDelegate performSelectorOnMainThread:#selector(refreshViewController:) withObject:#"YES" waitUntilDone:NO];
}// Control not come inside of if Condition.... From here i want to update the fourthViewController..
But control not go inside of the if condition. Could you please guide me where am doing wrong?
In my 4th ViewController.h
#import "AppDelegate"
#interface fourthViewController : UIViewController <ReloadViewControllerDelegate>
In my 4th ViewController.m
-(void) refreshViewController:(NSString *)result
{
NSLog(#"Result : %#", result);
}
Can anyone please help me to do this? Thanks in advance.
You need to declare your delegate like this:
#property (nonatomic, weak) IBOutlet id<ReloadViewControllerDelegate> delegate;
The id will work, but by using the <>, you can make sure that the delegate you assign is actually implementing the protocol, you might still have to make sure it responds to selector but that is only if some methods are declared as
#optional
make sure you synthesize it and most important make sure you set it, and it is not nil.
You're getting a warning because you are typing your delegate as an id. An id is a generic type, which means the compiler has no idea of what methods or properties might be available. In order to remove your warning, declare your delegate to be an NSObject:
#property (nonatomic, retain) NSObject <ReloadViewControllerDelegate> *refreshViewControllerDelegate;
By declaring as an NSObject, the compiler now knows about all the methods NSObject has, which will then allow you to call:
-performSelectorOnMainThread:withObject:waitUntilDone:
on your delegate without warnings. Good luck!
Try this:
#protocol ReloadViewControllerDelegate <NSObject>
-(void) refreshViewController:(NSString *)result;
#end
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (weak) id <ReloadViewControllerDelegate>refreshViewControllerDelegate;
#end
In AppDelegate.m
#implementation AppDelegate
#synthesize window, refreshViewControllerDelegate;
...
here Tab4ViewController is name of class.
if ([Tab4ViewController conformsToProtocol:#protocol(ReloadViewControllerDelegate)])
{
[refreshViewControllerDelegate performSelectorOnMainThread:#selector(refreshViewController:) withObject:#"YES" waitUntilDone:NO];
}
...
#end
#import "AppDelegate.h"
#interface Tab4ViewController<ReloadViewControllerDelegate>
...
#end
#implementation Tab4ViewController
...
appDelegate.refreshViewControllerDelegate = self;
...
#end
You are calling this code:
if ([refreshViewControllerDelegate conformsToProtocol:#protocol(ReloadViewControllerDelegate)])
But refreshViewControllerDelegate is this:
id refreshViewControllerDelegate;
conformsToProtocol checks to see if the object declares that it conforms to the protocol, which yours does not. If you want to specify conformity to a protocol you need to:
id<ReloadViewControllerDelegate> refreshViewControllerDelegate;
EDIT
OK, on the performSelectorOnMainThread problem... That method is provided in a category for NSThread, and is not declared in the NSObject protocol. So, if you want to call that, then you need to declare your type as NSObject, which conforms to your protocol.
NSObject<ReloadViewControllerDelegate> refreshViewControllerDelegate;
EDIT
OK, it looks like this is not a simple question about using a protocol, but a full tutorial. Since SO isn't the place for such, I'll try to give a brief one...
A protocol is an interface declaration.
#protocol ReloadChatViewControllerDelegate <NSObject>
- (void)refreshViewController:(NSString *)result;
#end
That says there is a new protocol in town, with the name ReloadChatViewControllerDelegate and it also conforms to the NSObject protocol. Any class that adopts the new protocol must provide an implementation of refreshViewController. You can make a protocol method optional, by putting in an #optional section.
#protocol ReloadChatViewControllerDelegate <NSObject>
- (void)refreshViewController:(NSString *)result;
#optional
- (void)optRefresh;
#end
Now, let's leave the adoption of the protocol for later. Say you are writing generic code, and you just want to know if the object you are given conforms to the protocol, and if so, invoke a method on it. Something like...
#interface Bar : NSObject
#property (nonatomic, weak) NSObject<ReloadChatViewControllerDelegate> *refreshViewControllerDelegate;
- (void)blarg;
#end
Now, the Bar class is providing a delegate property, so that it can be give some object that will help it do some work. However, that delegate object must at least be an NSObject, and conform to the ReloadChatViewControllerDelegate protocol.
Now, ObjC (and C) is quite permissive, so you can force an object to be any type you want, but then you deserve the crash you get. Now, when blarg is called, the delegate is notified to do some work.
Since the property type of the delegate already says it conforms to the given protocol, there is no need to check for conformity. We can just call the delegate method. Note that we must see if the object implements any optional protocol methods.
#implementation Bar
#synthesize refreshViewControllerDelegate = _refreshViewControllerDelegate;
- (void)blarg {
// Do something, then invoke the delegate
[self.refreshViewControllerDelegate
performSelectorOnMainThread:#selector(refreshViewController:)
withObject:#"YES"
waitUntilDone:NO];
if ([self.refreshViewControllerDelegate respondsToSelector:#selector(optRefresh)]) {
[self.refreshViewControllerDelegate optRefresh];
}
}
#end
However, if you want to be generic, and accept any object as a delegate (maybe you want to make it optional that the delegate conforms to some given protocol), then you can accept a plain id and then check to see it it conforms. In that case, you could declare your delegate as just an id (or some other type).
#property (nonatomic, weak) id refreshViewControllerDelegate;
Now, in your code, you need to check for conformity.
- (void)blarg {
// Do something, then invoke the delegate
if ([self.refreshViewControllerDelegate
conformsToProtocol:#protocol(ReloadChatViewControllerDelegate)]) {
[self.refreshViewControllerDelegate
performSelectorOnMainThread:#selector(refreshViewController:)
withObject:#"YES" waitUntilDone:NO];
if ([self.refreshViewControllerDelegate
respondsToSelector:#selector(optRefresh)]) {
[self.refreshViewControllerDelegate optRefresh];
}
}
}
OK, now you have a protocol defined, and you have code that calls methods on the protocol. Two caveats.
First, the delegate has to be set to an object. nil will respond false for any method, so it will of course not conform, nor do anything when sent any message.
Second, you have to make sure that your delegate declares conformity to the protocol. Just implementing the methods is not conformity. If a class does not explicitly specify that is conforms to a protocol, then conformsToProtocol will return false, even if it implements the methods of the protocol.
So, let's specify some class that will act as our delegate by conforming to the protocol.
#interface Foo : NSObject<ReloadChatViewControllerDelegate>
- (void)refreshViewController:(NSString *)result;
#end
#implementation Foo
- (void)refreshViewController:(NSString *)result {
NSLog(#"Look, ma, I'm refreshed with %#", result);
}
#end
It conforms to the protocol, provides an implementation for the mandatory method, and omits the optional one.
Now, if you ran this code, you should see that marvelous code in all its splendor.
Foo *foo = [[Foo alloc] init];
Bar *bar = [[Bar alloc] init];
bar.refreshViewControllerDelegate = foo;
[bar blarg];

I am losing my default UIScrollViewdelegate methods when I subclass it

I try to subclass the UScrollview but it ends up losing the default UIScrollview delegate method.
#import <UIKit/UIKit.h>
#protocol myscrollviewDelegate <NSObject>
-(void) myscrollview_return;
#end
#interface myscrollview : UIScrollView <UIScrollViewDelegate> {
id<myscrollviewDelegate> delegate;
}
#property(nonatomic, assign) id<myscrollviewDelegate> delegate;
#end
(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
never get called when scroll.
what's wrong? Can I subclass the UIScrollview and add additonal delegate and at the same times keeping the original delegates??
You are not adding a property, but overriding it, as UIScrollView already has a delegate property. When you set a delegate using the new property, the reference will be stored in the instance variable you added, not in the private instance variable of the original UIScrollView.
My theory is that the implementation of UIScrollView accesses the instance variable without using the property. I haven't verified it, but try not adding a new ivar and overriding the delegate property.
You can do this without creating a second delegate property.
First, make your delegate protocol inherit from UIScrollViewDelegate:
#protocol myscrollviewDelegate <NSObject, UIScrollViewDelegate>
Then, declare the delegate property in your header for your class:
#interface myscrollview : UIScrollView <UIScrollViewDelegate>
#property(nonatomic, assign) id<myscrollviewDelegate> delegate;
And the key is to not synthesize the property, but rather make it dynamic in your implementation file.
#implementation myscrollview
#dynamic delegate;
...
This is because You implement the delegate methods with id id delegate; I hope so
so change the name of delegate. instead using delegate use other name like "delegateSomeClass" etc
Now the delegates method of UIscrollView calls
hope it will clear :)

how to extend a protocol for a delegate in objective C, then subclass an object to require a conforming delegate

I want to subclass UITextView, and send a new message to the delegate. So, I want to extend the delegate protocol. What's the correct way to do this?
I started out with this:
interface:
#import <Foundation/Foundation.h>
#class MySubClass;
#protocol MySubClassDelegate <UITextViewDelegate>
- (void) MySubClassMessage: (MySubClass *) subclass;
#end
#interface MySubClass : UITextView {
}
#end
implementation:
#import "MySubClass.h"
#implementation MySubClass
- (void) SomeMethod; {
if ([self.delegate respondsToSelector: #selector (MySubClassMessage:)]) {
[self.delegate MySubClassMessage: self];
}
}
#end
however with that I get the warning: '-MySubClassMessage:' not found in protocol(s).
I had one way working where I created my own ivar to store the delegate, then also stored the delegate using [super setDelegate] but that seemed wrong. perhaps it's not.
I know I can just pass id's around and get by, but My goal is to make sure that the compiler checks that any delegate supplied to MySubClass conforms to MySubClassDelegate protocol.
To further clairfy:
#interface MySubClassTester : NSObject {
}
#implementation MySubClassTester
- (void) one {
MySubClass *subclass = [[MySubClass alloc] init];
subclass.delegate = self;
}
#end
will produce the warning: class 'MySubClassTester' does not implement the 'UITextViewDelegate' protocol
I want it to produce the warning about not implementing 'MySubClassDelegate' protocol instead.
The UITextView defines its delegate as
#property(nonatomic, assign) id<UITextViewDelegate> delegate
meaning it conforms to UITextViewDelegate, and that's what compiler checks. If you want to use the new protocol, you need to redefine delegate to conform to your protocol:
#interface MySubClass : UITextView {
}
#property(nonatomic, assign) id<MySubClassDelegate> delegate
#end
The compiler shouldn't give any more warnings.
[Update by fess]
... With this the compiler will warn that the accessors need to be implemented... [I implemented this:]
-(void) setDelegate:(id<MySubClassDelegate>) delegate {
[super setDelegate: delegate];
}
- (id) delegate {
return [super delegate];
}
"
[My update]
I believe it should work if you only make a #dynamic declaration instead of reimplementing the method, as the implementation is already there:
#dynamic delegate;
For anyone still interested, this can be done quite simply like this (for sake of the example, I subclass UIScrollView):
#protocol MySubclassProtocol <UIScrollViewDelegate>
#required
-(void)myProtocolMethod;
#end
#interface MySubClass : UIScrollView
#property (nonatomic, weak) id <MySubclassProtocol> delegate;
The most important detail here is the part between the <> after your protocol's name which, put in a simple manner, signals you're extending that protocol.
In your implementation, all you need to do then is:
#synthesize delegate;
And you're done.
You need to extend the super protocol:
#protocol MYClassProtocol <SuperClassProtocol>
-(void)foo;
#end
after that DON'T (!!!) create the #property for the delegate otherwise you override the original delegate object, but simply override the method:
- (id<MYClassProtocol>)delegate
{
return (id<MYClassProtocol>)[super delegate];
}
now you can use the delegate in the classic way:
[self.delegate foo];
[self.delegate someSuperClassDelegateMethod];
Given that MySubClassMessage: is optional, you should be able to simple do a simple:
- (void) SomeMethod {
SEL delegateSelector = #selector(MySubClassMessage:);
if ([self.delegate respondsToSelector:delegateSelector]) {
[self.delegate performSelector:delegateSelector withObject:self];
}
}
The complier should still check that the implementing class conforms to your protocol (or at least claim to in the header) and you won't get the error you described.

Warning when communicating context from controller to NSView with custom methods

Coding against UIKit for iPhone.
Setup, with relevant detail:
SomeView.h:
#import <UIKit/UIKit.h>
#interface SomeView : UIView {
SomeObject *myObject;
}
#property (assign) SomeObject *myObject;
-(void) doSomething;
#end
SomeView.m:
#import "SomeView.h"
#implementation SomeView
#synthesize myObject;
- (void)doSomething {
NSLog(#"doing something");
}
- (void) drawRect:(CGRect)rect {
// drawing is based on myObject
}
#end
Controller.h:
#import <UIKit/UIKit.h>
#import "SomeView.h"
#interface Controller : NSObject {
IBOutlet UIView *someView;
}
#end
Controller.m:
#import "Controller.h"
#implementation Controller
-(void)awakeFromNib {
[someView doSomething];
[someView setSomeObject:someObject];
}
#end
I am instantiating the controller object in Interface Builder, and SomeView is the class of one of my custom UIViews in my app's main window.
Now, the questions:
1) when I run the above, I get warnings for both lines: "Warning: 'UIView may not respond to 'doSomething'" and similar warning for setSomeObject. Why? (The code actually seems to work, but I don't like seeing the warnings.)
2) is this the right way of doing things? What I am really after, is making SomeView aware of someObject, so that when drawRect for SomeView is called, it can change its behavior based on current state of someObject. I don't need to have the object directly in SomeView; I could have it in the controller, but the view still needs some information from it that may change at runtime.
You declared someView as an instance of UIView, but doSomething is a method of SomeView. So it is correct — the class you told the compiler that the variable points to does not respond to that message. If you don't want warnings, you'll have to make it a SomeView * instead of a UIView *.
Otherwise, your general architecture looks OK to me.