Best way to implement Enums with Core Data

前端 未结 9 1593
天命终不由人
天命终不由人 2020-11-28 17:55

What is the best way to bind Core Data entities to enum values so that I am able to assign a type property to the entity? In other words, I have an entity called Item<

9条回答
  •  北海茫月
    2020-11-28 18:22

    You'll have to create custom accessors if you want to restrict the values to an enum. So, first you'd declare an enum, like so:

    typedef enum {
        kPaymentFrequencyOneOff = 0,
        kPaymentFrequencyYearly = 1,
        kPaymentFrequencyMonthly = 2,
        kPaymentFrequencyWeekly = 3
    } PaymentFrequency;
    

    Then, declare getters and setters for your property. It's a bad idea to override the existing ones, since the standard accessors expect an NSNumber object rather than a scalar type, and you'll run into trouble if anything in the bindings or KVO systems try and access your value.

    - (PaymentFrequency)itemTypeRaw {
        return (PaymentFrequency)[[self itemType] intValue];
    }
    
    - (void)setItemTypeRaw:(PaymentFrequency)type {
        [self setItemType:[NSNumber numberWithInt:type]];
    }
    

    Finally, you should implement + keyPathsForValuesAffecting so you get KVO notifications for itemTypeRaw when itemType changes.

    + (NSSet *)keyPathsForValuesAffectingItemTypeRaw {
        return [NSSet setWithObject:@"itemType"];
    }
    

提交回复
热议问题