首页 > 解决方案 > 无法通过委托访问协议方法

问题描述

通过委托访问协议方法时出现以下错误:“选择器'lostConnection'没有已知的实例方法”

斯威夫特协议:

@objc protocol GameDelegate {
    func lostConnection()
}

Objective C 游戏文件

//game.h

@protocol GameDelegate;
@interface SSStreamManager : NSObject 

@property (assign) id<GameDelegate> delegate

@end

调用协议方法时出错

[self.delegate lostConnection]; // No known instance method for selector 'lostConnection'

标签: objective-cswiftprotocols

解决方案


这变得荒谬,因为您一直拒绝显示任何真实代码。因此,我将向展示一些真实的代码。以下是 iOS 应用项目中的三个文件:

ViewController.swift

import UIKit
@objc protocol GameDelegate {
    func lostConnection()
}
class ViewController: UIViewController {
}

东西.h

#import <Foundation/Foundation.h>
@protocol GameDelegate;
@interface Thing : NSObject
@property (assign) id<GameDelegate> delegate;
@end

东西.m

#import "Thing.h"
#import "MyApp-Swift.h"
@implementation Thing
- (void) test {
    [self.delegate lostConnection];
}
@end

编译。去吧,照样做。


推荐阅读