Sylphos
Sylphos

Reputation: 178

How to create a protocol in objective-C

I want to create a Utils file, to have some functions and use them in some classes, but I'm not sure of how to do it.

I have:

Utils.h

#import <Foundation/Foundation.h>

@protocol Utils 

@optional

-(NSString*)colorToHex:(UIColor*)color;

@end

@interface Utils : NSObject 

@end

Utils.m

#import "Utils.h"

@implementation Utils

-(NSString*)colorToHex:(UIColor*)color{
    return @"Working";
}

@end

mainClass.h (snippet)

@interface StyleTableViewController : UITableViewController <Utils>

mainClass.m (the call)

NSString *myString = [self colorToHex:color];
NSLog(@"%@",myString);

And it crashes when it calls the function. What should I do?

Thanks

Upvotes: 0

Views: 431

Answers (2)

Roger
Roger

Reputation: 4797

Another option would be to add a category Utils to UIColor. Not exactly what you asked for but it solves your problem more elegantly than using a protocol.

Upvotes: 1

Orbatrix
Orbatrix

Reputation: 66

When you state that your class conforms to a protocol (by adding ) you tell the compiler that this class implements all the methods defined in the protocol. A Protocol is not a class - it's just a list of methods. So in your code, you had a protocol call Utils, and a class called Utils. You conformed to the protocol, but did not implement the methods, which is why the program crashed when you tried to call colorToHex. What you need to do in your case is create a Util object in your StyleTableViewController and use it to call the colorToHex method, or make the colorToHex method a class method and call it from the Util class when needed. Another option would be to make StyleTableViewController a subclass of Utils, but I doubt this will be a good design here.

Upvotes: 2

Related Questions