objective-c - 导入头文件后尝试使用另一个类的参数创建类方法时出现类型错误
问题描述
所以基本上我在这里创建 2 个类:Patient 和 Doctor
我想要做的是我想创建一个名为“requestMedicationForPatient”的实例方法,它将患者实例作为参数。所以我做了这样的事情
-(void)requestMedicationForPatient: (Patient*) patient;
在 Doctor.h 文件中。而且我已经在 Doctor.h 和 Doctor.m 文件中导入了 Patient.h 文件。为什么它不起作用?
患者.h:
#import <Foundation/Foundation.h>
#import "Doctor.h"
NS_ASSUME_NONNULL_BEGIN
@interface Patient : NSObject
@property NSString* name;
@property NSInteger age;
@property (nonatomic) BOOL hasValidHealthCard;
- (instancetype)initWithName:(NSString*) name andAge: (int) age;
@end
NS_ASSUME_NONNULL_END
患者.m:
#import "Patient.h"
#import "Doctor.h"
@implementation Patient
- (instancetype)initWithName:(NSString*) name andAge: (int) age
{
self = [super init];
if (self) {
_age = age;
_name = name;
}
return self;
}
@end
医生.h:
#import <Foundation/Foundation.h>
#import "Patient.h"
NS_ASSUME_NONNULL_BEGIN
@interface Doctor : NSObject
@property (nonatomic)NSString* name;
@property (nonatomic)NSString* specialization;
@property (nonatomic)NSMutableSet* patients;
- (instancetype)initWithName: (NSString*) name andSpecialization: (NSString*) specialization;
-(void)requestMedicationForPatient: (Patient*) patient;
@end
NS_ASSUME_NONNULL_END
医生.m:
#import "Doctor.h"
#import "Patient.h"
@implementation Doctor
- (instancetype)initWithName: (NSString*) name andSpecialization: (NSString*) specialization
{
self = [super init];
if (self) {
_name = name;
_specialization = specialization;
}
return self;
}
@end
我应该能够使用 Patient 类型的参数创建该方法,对吗?但它说 Expected 一种类型。
解决方案
您正在将 Patient.h 导入 Doctor.h,并且正在将 Doctor.h 导入 Patient.h。始终避免此类循环导入。还要避免在另一个头文件中不必要地导入一个头文件。
Patient.h 中没有任何内容引用 Doctor.h 中的任何内容,因此您不应该在 Patient.h 文件中导入 Doctor.h。
您还应该从 Doctor.h 中删除 Patient.h 的导入。为了使编译器满意,您可以提供对Patient
using的前向引用@class Patient;
。
您更新的 Doctor.h 应该是:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class Patient;
@interface Doctor : NSObject
@property (nonatomic) NSString* name;
@property (nonatomic) NSString* specialization;
@property (nonatomic) NSMutableSet* patients;
- (instancetype)initWithName:(NSString *)name andSpecialization:(NSString*)specialization;
- (void)requestMedicationForPatient:(Patient *)patient;
@end
NS_ASSUME_NONNULL_END
推荐阅读
- python - 如何调整numpy数组的大小?
- kubernetes - Kubernetes kubectl 补丁 pod 与删除/创建 pod
- swift - 快速比较三个枚举
- python - Python pivot_table - 添加差异列
- c - 如何使用 write() 或 fwrite() 将数据写入终端(stdout)?
- powershell - 将从文件中读取的变量传递给调用命令
- r - 尽管在常规 R 脚本中工作,但命令无法在 RMarkdown 中运行
- api - 无法使用 Az DevOps Pipelines API 6.0-preview.1 创建新的管道
- android - 预期 1 个字节,但收到 3 个
- flutter - 更新时清除的 TextField 列表 - Flutter