简体   繁体   中英

iOS Core Data - how to save Tuple property

I'm in process of adding Core Data to my app, started out with a struct like this:

struct Expense: Equatable{
    let id: String = UUID().uuidString
    var name: String
    var description: String
    var category: String
    var nextBill: Date
    var billingCycle: (Int, String)
    var currency: Currency?
    var price: Decimal
}

Reading documentation look like I'll need to convert it to a class

@objc(Expense)
public class Expense: NSManagedObject {
    let id: String = UUID().uuidString
    var name: String
    var description: String
    var category: String
    var nextBill: Date
    var billingCycle: (Int, String)
    var currency: Currency?
    var price: Decimal
}

However this appears to have issue with the billingCycle property which is a tuple value ( example of value: 1 per week, 1 per month, 3 per year)

I'm thinking of splitting the billingCycle property into 2 new properties: billingCycleInt and billingCycleString . Would this be the best approach or there is other way?

That would be best. Core Data is— internally— still very much oriented toward Objective-C. As such it has no idea about Swiftisms like tuples. There are other approaches that could work, like trying to get NSCoding to work for this property, but they would all be significantly more complex.

If you'd like to keep the tuple, you might consider adding the two properties you mention and then converting the tuple into a computed property that looks up the values of the other two. Then you can use a Swift tuple where it's convenient but still work with Core Data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM