Search code examples
objective-ccore-dataprotocolscategoriesnsmanagedobject

Property requires method to be defined in NSManagedObject subclass


I have some protocol like this:

@protocol UserProtocol <NSObject>

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

@end

Then I created some actual class that implements that:

@interface User : NSObject <UserProtocol>

@end

Now I need another implementation that uses CoreData so I created CDUser entity (Xcode also generates category for that):

// 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 actually implements UserProtocol but I have warnings like so for all properties:

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

If I add @dynamic uid; again in CDBook.m then I get the following error:

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

How can I solve these warnings in a proper way?


Solution

  • Cause CDUser doesn't implement this protocol. Use protocol on category instead.

    @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