简体   繁体   中英

How To Solve No Type or Protocol Named Error In Xcode 7?

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 > { }

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.

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 (eg OtherClass.h). You should declare in OtherClass.ha 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)

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