Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

core data - Swift: Storing states in CoreData with enums

I want to store an enum state for a managed object within CoreData

enum ObjStatus: Int16 {
    case State1 = 0
    case State2 = 1
    case State3 = 3
}

class StateFullManagedObject: NSManagedObject {
    @NSManaged var state: Int16
}

The last step would be converting the state var of StateFullManagedObject to ObjStatus for direct comparison, which isn't working for me. For example, I can't use the == operator between and Int16 and the Int16 enum. The compile time error I get is

Int16 is not convertible to 'MirrorDisposition'

. See the conditional below:

var obj: StateFullManagedObject = // get the object

if (obj.state == ObjStatus.State1) { // Int16 is not convertible to 'MirrorDisposition'

}

How can I compare/assign between an Int16 and an enum?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can declare your enum as @objc. Then it all automagically works. Here's a snippet from a project I'm working on.

// Defined with @objc to allow it to be used with @NSManaged.
@objc enum AgeType: Int32
{
    case Age                = 0
    case LifeExpectancy     = 1
}

/// The age type, either Age or LifeExpectancy.
@NSManaged var ageType: AgeType

In the Core Data model, ageType is set to type Integer 32.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...