首页 > 解决方案 > 导入头文件后尝试使用另一个类的参数创建类方法时出现类型错误

问题描述

所以基本上我在这里创建 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 一种类型。

标签: objective-cclass

解决方案


您正在将 Patient.h 导入 Doctor.h,并且正在将 Doctor.h 导入 Patient.h。始终避免此类循环导入。还要避免在另一个头文件中不必要地导入一个头文件。

Patient.h 中没有任何内容引用 Doctor.h 中的任何内容,因此您不应该在 Patient.h 文件中导入 Doctor.h。

您还应该从 Doctor.h 中删除 Patient.h 的导入。为了使编译器满意,您可以提供对Patientusing的前向引用@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

推荐阅读