属性 需要在 NSManagedObject 子类中定义方法

Property requires method to be defined in NSManagedObject subclass

我有这样的协议:

@protocol UserProtocol <NSObject>

@property (nonatomic, strong) NSNumber *uid;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *rating;

@end

然后我创建了一些实际的 class 来实现:

@interface User : NSObject <UserProtocol>

@end

现在我需要另一个使用 CoreData 的实现,所以我创建了 CDUser 实体(Xcode 也为此生成了类别):

// CDUser.h
@interface CDUser : NSManagedObject <UserProtocol>

@end

// CDUser+CoreDataProperties.h
@interface CDUser (CoreDataProperties)

@property (nullable, nonatomic, retain) NSNumber *uid;
@property (nullable, nonatomic, retain) NSString *name;
@property (nullable, nonatomic, retain) NSNumber *rating;

@end

// CDUser+CoreDataProperties.m
@implementation CDUser (CoreDataProperties)

@dynamic uid;
@dynamic name;
@dynamic rating;

@end

CDUser 实际上实现了 UserProtocol 但我对所有属性都有这样的警告:

Property 'uid' requires method 'uid' to be defined - use @synthesize, @dynamic or provide a method implementation in this class implementation

如果我在 CDBook.m 中再次添加 @dynamic uid; 然后我得到以下错误:

Property declared in category 'CoreDataProperties' cannot be implemented in class implementation

如何正确解决这些警告?

原因CDUser 没有实现这个协议。请改用类别上的协议。

@interface CDUser : NSManagedObject

@end

// CDUser+CoreDataProperties.h
@interface CDUser (CoreDataProperties)  <UserProtocol>

@property (nullable, nonatomic, retain) NSNumber *uid;
@property (nullable, nonatomic, retain) NSString *name;
@property (nullable, nonatomic, retain) NSNumber *rating;

@end