How To Solve No Type or Protocol Named Error In Xc

2019-04-10 17:04发布

问题:

I m trying to passing values from second class to first class for that I am using protocol and delegate process. Whenever I run my program I am facing below Issue.

No Type or Protocol Named 'locateMeDelegate'

Viewcontroller A .h

@interface first : UIViewController < locateMeDelegate > { }

回答1:

In my case the issue was caused by importing the delegate's header file to the delegator's class .h file. This seems to create a sort of vicious circle. As soon as I deleted the import statement of the delegate's header from the delegator's .h file, the error went away.



回答2:

Tipically, if you intend your protocol to be used by other classes you must declare it in the header file like this:

// MyClass.h

@protocol MyProtocol;

@interface MyClass : NSObject
@end

@protocol MyProtocol
- (void) doSomething: (MyClass*) m;
@end

After you declare it, you should implement the methods of the protocol in the implementation file, which should conform to the protocol like this:

// MyClass.m

@implementation MyClass <MyProtocol>

pragma mark - MyProtocol methods

- (void) doSomething: (MyClass *)m {
     // method body
}

@end

After these two steps you're ready to use you protocol in any class you desire. For example, let's say we want to pass data to MyClass from other class (e.g. OtherClass.h). You should declare in OtherClass.h a property so that we can refer to MyClass and execute the protocol. Something like this:

// OtherClass.h

#import MyClass.h

@interface OtherClass : NSObject

@property (weak) id<MyProtocol> delegate;

@end

You don't forget to import the header file where you declared your protocol, otherwise Xcode will prompt No Type or protocol named "MyProtocol"

  • id<MyProtocol> delegate; means you can set as the delegate of OtherClass any object (id) that conforms to the MyProtocol protocol (<MyProtocol>)

Now you can create an OtherClass object from MyClass and set its delegate property to self. Like this:

// MyClass.m

- (void)viewDidLoad() {
     OtherClass *otherClass = [[OtherClass alloc] init];
     otherClass.delegate = self;
}
  • It's possible to set the delegate to self because the delegate can be any object and MyClass conforms to MyProtocol.

I hope this can help. If you want to know more about protocols you can refer to this two websites:

Working with Protocols - Apple Documentation

Ry's Objective-C Tutorial (This one is easy to pick up)