简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM