zio
zio

Reputation: 2225

How to pass values to a @protocol

I'm trying to implement a protocol.

I've looked at the documentation here and I understand the concepts although I think I'm missing a few things.

I'm trying to make a view that the user taps on a filename in a table view triggering 'didSelectRowAtIndexPath' which will in turn notify the delegate that the user has selected a file (triggering didSelectFileName in the delegate) and passing the fileName. I've declared the protocol as follows;

@protocol FileList <NSObject>
- (void)didSelectFileName:(NSString *)fileName;    
@end

My questions are:

Upvotes: 2

Views: 282

Answers (2)

user142019
user142019

Reputation:

You cannot just send a message to a protocol (nor setting values). You send the message to a class that conforms to the protocol.


When you say a class conforms to a protocol (@interface MyClass : NSObject <MyProtocol> { etc) you can safely send any messages to the class with the selectors that conform to the methods in the protocol.

So if we take your protocol for example we can have a class that can send messages to a delegate:

@interface MyClass : NSObject {
  id<FileList> _delegate;
}

@end

@implementation MyClass

- someMethod {
  NSString *fn = @"Hello.";
  [_delegate didSelectFileName:fn];
}

@end

Just make sure you implement the methods that are in your protocol in you delegate.

You don't need to redefine the methods in the interface of your delegate class.


Here are some good reads about protocols:

Upvotes: 3

Rahul Vyas
Rahul Vyas

Reputation: 28730

//In table View method

- (void)tableView didSelectRowAtIndexPath....... {
UITableViewCell *cell = [tableView methodToGetCell];
if(delegate && [delegate respondsToSelector:@selector(didSelectFileName:)]){
[delegate didSelectFileName:cell.text];
}

Upvotes: 1

Related Questions