如何在Xcode 7中解决没有类型或协议命名错误? [英] How To Solve No Type or Protocol Named Error In Xcode 7?

查看:722
本文介绍了如何在Xcode 7中解决没有类型或协议命名错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将第二个中的值传递给第一个类,因为我正在使用 protocol 委托进程。每当我运行我的程序时,我面临着问题。

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.


没有类型或协议命名为'locateMeDelegate'

No Type or Protocol Named 'locateMeDelegate'

Viewcontroller A .h

Viewcontroller A .h

@interface first : UIViewController < locateMeDelegate > { }


推荐答案

简而言之,如果您打算使用您的协议其他类使用你必须在头文件中声明它如下:

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

完成这两个步骤后,您就可以在任何课程中使用协议你渴望。例如,假设我们想要从其他类(例如OtherClass.h)将数据传递给MyClass。您应该在OtherClass.h中声明一个属性,以便我们可以引用MyClass并执行协议。这样的事情:

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

你不要忘记导入头文件你声明了你的协议,否则Xcode会提示没有类型或协议名为MyProtocol

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; 表示你可以设置为 OtherClass 的任何对象( id )的委托符合 MyProtocol 协议(< MyProtocol>

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

现在,您可以从MyClass创建一个OtherClass对象,并将其delegate属性设置为self。像这样:

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




  • 可以将委托设置为self,因为委托可以是任何对象, MyClass 符合 MyProtocol

    • 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:

      使用协议 - Apple文档

      Ry的Objective-C教程(这个很容易上手)

      这篇关于如何在Xcode 7中解决没有类型或协议命名错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆