1

I have a UIView subclass called NumberPickerView. I'm writing a delegate method for it. The compiler won't let me pass an instance of NumberPickerView as an parameter in that method. What am I missing?

@protocol NumberPickerViewDelegate

-(void) numberPickerDidChangeSelection:(NumberPickerView *)numberPickerView;
//error: expected a type

@end


@interface NumberPickerView : UIView <UIScrollViewDelegate> {
     id <NumberPickerViewDelegate> delegate;
}
James White
  • 774
  • 1
  • 6
  • 18
  • Injectios answer is by far the most correct solution. With that said, how useful is `numberPickerDidChangeSelection:`? Wouldn't `numberPicker:(NumberPickerView *)numberPickerView didChangeSelection:(id)selection;` (where `id` is replaced by whatever represents the selection) be far more useful? Even a separate argument for the `from` and `to` change might be useful. – nhgrif Aug 23 '14 at 13:31
  • Possibly, but I don't really need to know the value at the time it's changed - just which picker has changed. In my current implementation NumberPickerView has a value property, and there are several on screen at once. I am getting the picker's value directly from its property, at the time I need it, so just need to know which one has been changed. Your implementation would also work. – James White Aug 23 '14 at 15:24

2 Answers2

3

Actually it CAN. At that point compiler doesn't know about NumberPickerView class

@class NumberPickerView;

add it over protocol declaration to let compiler know about that class... It's called forward declaration.

For better understanding check this out:

iPhone+Difference Between writing @classname & #import"classname.h" in Xcode

OR

move protocol declaration below the class NumberPickerView definition but in that case you should also add at top:

@protocol NumberPickerViewDelegate;

Not to get warnings using id<NumberPickerViewDelegate>delegate

Community
  • 1
  • 1
Injectios
  • 2,777
  • 1
  • 30
  • 50
3

You can change parameter type to id instead of NumberPickerView * and pass any class object afterword as bellow

@protocol NumberPickerViewDelegate

-(void) numberPickerDidChangeSelection:(id)numberPickerView;

@end


@interface NumberPickerView : UIView <UIScrollViewDelegate> {
     id <NumberPickerViewDelegate> delegate;
}
nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • Yes, this would compile. But a "wrong delegate" would no longer be detected by the compiler and cause a runtime exception later. – Martin R Aug 23 '14 at 13:26