【问题标题】:Not able to save a custom object array save to UserDefault in Swift 4无法在 Swift 4 中将自定义对象数组保存到 UserDefault
【发布时间】:2019-01-04 11:14:23
【问题描述】:

我在 GoogleStackOverflow 上搜索了大约 2 天,但没有运气。

我的自定义对象几乎是CNContact 对象的复制品。

struct Contact: Codable {

let fullName, phones, emails: String
let imageDataAvailable, expanded: Bool
let thumbnailImageData, imageData: Data
let contactType: Int
let identifier: String
let namePrifix, givenName, middleName, familyName, previousFamilyName, nameSuffix, nickName, organizationName, departmentName, jobTitle, phoneticGivenName, phoneticMiddleName, phoneticFamilyName, phoneticOrganizationName, note: String
let birthday, nonGregorianBirthday: DateComponents
let dates: [ContactDate]
let postalAddresses: [PostalAddress]
let urlAddresses: [UrlAddress]
let contactRelations: [ContactRelation]
let socialProfiles: [SocialProfile]
let instantMessageAddresses: [InstantMessageAddress]
let phoneNumbers: [PhoneNumber]
let emailAddresses: [Email]
}

struct PostalAddress: Codable {
    let label, street, subLocality, city, subAdministativeArea, state, postalCode, country, isoCountryCode: String
}

struct UrlAddress: Codable {
    let label, value: String
}

struct ContactRelation: Codable {
    let label, name: String
}

struct SocialProfile: Codable {
    let label, urlString, userName, userIdentifier, service: String
}

struct PhoneNumber: Codable {
    let label, stringValue: String
}

struct Email: Codable {
    let label, value: String
}

struct InstantMessageAddress: Codable {
    let label, userName, service: String
}

struct ContactDate: Codable {
    let label: String
    let value: DateComponents
}

我尝试将Contact 对象的数组保存到UserDefault,但它一直给我同样的错误。

请帮我解决这个问题。

编辑 1

我尝试使用下面的代码将数组转换为数据,但运气不好,我又遇到了一个错误

代码

do {
        let contactJson = try JSONSerialization.data(withJSONObject: arrContact, options: .prettyPrinted)
        CommonFunctions.setUserDefaultValue(key: WSKey.contacts.rawValue, value: contactJson)
    } catch let parsingError {
        print("Error", parsingError)
    }


错误

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“JSON 写入中的类型无效 (_SwiftValue)”

我在日志中带有debugDescription 命令的数组如下

"[Storedge.Contact(全名:\"Kate Bell\",电话:\"(555) 564-8583\n(415) 555-3695\",电子邮件:\"kate-bell@mac.com \", imageDataAvailable: false, expand: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"177C371E-701D-42F8-A03B-C61CA31627F6\", namePrifix: \"\", givenName: \"Kate\",middleName:\"\",familyName:\"Bell\",previousFamilyName:\"\",nameSuffix:\"\",nickName:\"\",organizationName:\"Creative Consulting\" , departmentName: \"\", jobTitle: \"Producer\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\" , 生日: 日历: 公历 (固定) 年: 1978 月: 1 天: 20 isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , 日期: [], postalAddresses: [Storedge.PostalAddress(label: \"$!! $\",街道:\"165 Davis Street\",分区:\"\",城市:\"Hillsborough\",分区:\"\",州:\"CA\",邮政编码: \"94010\",国家:\"\",iso CountryCode: \"us\")], urlAddresses: [Storedge.UrlAddress(label: \"$!!$\", value: \"www.icloud.com\")], contactRelations : [], socialProfiles: [], InstantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(555) 564-8583\ ")、Storedge.PhoneNumber(label:\"$!!$\"、stringValue:\"(415) 555-3695\")]、emailAddresses:[Storedge.Email(label:\ "$!!$\",值:\"kate-bell@mac.com\")]),Storedge.Contact(fullName:\"Daniel Higgins\",电话:\"555 -478-7672\n(408) 555-5270\n(408) 555-3514\",电子邮件:\"d-higgins@mac.com\",imageDataAvailable:false,扩展:false,thumbnailImageData:0 字节, imageData: 0 bytes, contactType: 0, identifier: \"AB211C5F-9EC9-429F-9466-B9382FF61035\", namePrifix: \"\", givenName: \"Daniel\", middleName: \"\", familyName: \ "Higgins\", previousFamilyName: \"\", nameSuffix: \"Jr.\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName : \"\", 拼音Middl eName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"Sister: Emily\",birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"332 Laguna Street\", subLocality: \"\", city: \"Corte Madera\", subAdministativeArea : \"\", state: \"CA\", postalCode: \"94925\", country: \"USA\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles:[],instantMessageAddresses:[],phoneNumbers:[Storedge.PhoneNumber(label:\"$!!$\",stringValue:\"555-478-7672\"),Storedge。 PhoneNumber(label: \"$!!$\", stringValue: \"(408) 555-5270\"), Storage.PhoneNumber(label: \"$!!$\", stringValue: \"(408) 555-3514\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \" d-higgins@mac.com\")]),Storedge.Contact(全名:\"John Appleseed\",电话:\"888-555-5512\n888-555-1212\",电子邮件:\"John- Appleseed@mac.com\", imageDa taAvailable: false, 展开: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"410FE041-5C4E-48DA-B4DE-04C15EA3DBAC\", namePrifix: \"\", givenName: \"John \", middleName: \"\", familyName: \"Appleseed\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \" \", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"College roommate\", 生日: calendar : gregorian (fixed) year: 1980 month: 6 day: 22 isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\",街道:\"3494 Kuhl Avenue\",子区域:\"\",城市:\"Atlanta\",子行政区:\"\",州:\"GA\",邮政编码:\"30303\ ",国家:\"USA\",isoCountryCode:\"us\"),Storedge.PostalAddress(label:\"$!!$\",街道:\"1234 Laurel Street\" , subLocality: \"\", 城市: \"Atlanta\ ", subAdministativeArea: \"\", state: \"GA\", postalCode: \"30303\", country: \"USA\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"888-555-5512\") , Storage.PhoneNumber(label: \"$!!$\", stringValue: \"888-555-1212\")], emailAddresses: [Storedge.Email(label: \"$!!$\",值:\"John-Appleseed@mac.com\")]),Storedge.Contact(fullName:\"Anna Haro\",电话:\"555-522- 8243\",电子邮件:\"anna-haro@mac.com\",imageDataAvailable:false,扩展:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符:\"F57C8277-585D-4327- 88A6-B5689FF69DFE\",namePrifix:\"\",givenName:\"Anna\",middleName:\"\",familyName:\"Haro\",previousFamilyName:\"\",nameSuffix:\"\", nickName:\"Annie\",organizationName:\"\",departmentName:\"\",jobTitle:\"\",phoneticGivenName:\"\",phoneticMiddleName:\"\",语音FamilyName:\"\",phoneticOrganizationName:\"\",注:\"\",生日:日历:公历(固定)年:1985 月:8 天:29 isLeapMonth:false,nonGregorianBirthday:isLeapMonth:false,日期: [Storedge.ContactDate(label: \"$!!$\", value: calendar: gregorian (fixed) year: 2002 month: 2 day: 15 isLeapMonth: false ), Storage.ContactDate(label : \"$!!$\", value: calendar: gregorian (fixed) year: 2002 month: 2 day: 15 isLeapMonth: false )], postalAddresses: [Storedge.PostalAddress(label: \ "$!!$\",街道:\"1001 Leavenworth Street\",子地区:\"\",城市:\"Sausalito\",子行政区:\"\",州:\ "CA\",postalCode:\"94965\",国家:\"USA\",isoCountryCode:\"us\")],urlAddresses:[],contactRelations:[],socialProfiles:[],instantMessageAddresses:[] , phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"555-522-8243\")], emailAddresses: [Storedge.Email(label: \ "$!!$\",值:\"anna-haro@mac.com\")]),存储dge.Contact(全名:\"Hank M. Zakroff\",电话:\"(555) 766-4823\n(707) 555-1854\",电子邮件:\"hank-zakroff@mac.com\", imageDataAvailable: false, expand: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"2E73EE73-C03F-4D5F-B1E8-44E85A70F170\", namePrifix: \"\", givenName: \"Hank \", middleName: \"M.\", familyName: \"Zakroff\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"Financial Services Inc.\ ", departmentName: \"\", jobTitle: \"Portfolio Manager\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \" \", 生日: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , 日期: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"1741 Kearny Street\", subLocality: \"\", city: \"San Rafael\", subAdministativeArea: \"\", state: \"CA\", postalCode: \"94901\", country: \"\" , isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], InstantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(555) 766-4823 \"), Storage.PhoneNumber(label: \"$!!$\", stringValue: \"(707) 555-1854\")], emailAddresses: [Storedge.Email(label: \"$!!$\",值:\"hank-zakroff@mac.com\")]),Storedge.Contact(fullName: \"David Taylor\",电话:\" 555-610-6679\",电子邮件:\"\",imageDataAvailable:false,扩展:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符:\"E94CD15C-7964-4A9B-8AC4-10D7CFB791FD \", namePrifix: \"\", givenName: \"David\", middleName: \"\", familyName: \"Taylor\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \ "\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \" \",注意:\"在 Cole\\'s Little League Baseball Team 中比赛\n\",生日:日历:gregorian (fixe d) 年:1998 月:6 天:15 isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\" , 街道: \"1747 Steuart Street\", subLocality: \"\", city: \"Tiburon\", subAdministativeArea: \"\", state: \"CA\", postalCode: \"94920\", country : \"USA\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"555-610-6679\")], emailAddresses: []), Storedge.Contact(fullName: \"mavya.soni@jayatma.com \",电话:\"\",电子邮件:\"mavya.soni@jayatma.com\",imageDataAvailable:false,扩展:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符:\"F01A8F75-B1E0 -4B72-A017-6FDE693BE4E4\",namePrifix:\"\",givenName:\"mavya.soni@jayatma.com\",middleName:\"\",familyName:\"\",previousFamilyName:\"\" , nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \ “\”,生日:isLeapMonth:false,nonGregorianBirthday:isLeapMonth:false,日期:[],postalAddresses:[],urlAddresses:[],contactRelations:[],socialProfiles:[],instantMessageAddresses:[],phoneNumbers:[] , emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"mavya.soni@jayatma.com\")]), Storage.Contact(fullName: \ "Dimple Shah\",电话:\"\",电子邮件:\"\",imageDataAvailable:false,扩展:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符:\"4B0CE4C4-6569- 4936-8C45-34A15725DF9D\",namePrifix:\"\",givenName:\"Dimple\",middleName:\"\",familyName:\"Shah\",previousFamilyName:\"\",nameSuffix:\"\ ", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\" , 拼音或ganizationName: \"\", note: \"\",birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations: [], socialProfiles: [] ,即时消息地址:[],电话号码:[],电子邮件地址:[]),Storedge.Contact(全名:\“yash.soni@jayatma.com \”,电话:\“\”,电子邮件:\“yash.soni@ jayatma.com\",imageDataAvailable:false,expanded:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符:\"36C2E9A2-3955-49C7-BCED-02CDD1622E69\",namePrifix:\"\" , givenName: \"yash.soni@jayatma.com\", middleName: \"\", familyName: \"\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\",组织名称:\"\",部门名称:\"\",职位名称:\"\",phoneticGivenName:\"\",phoneticMiddleName:\"\",phoneticFamilyName:\"\",phoneticOrganizationName:\"\",注意: \"\", 生日: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , 日期: [], postalAddresses: [], urlAddresses: [], conta ctRelations: [], socialProfiles: [], InstantMessageAddresses: [], phoneNumbers: [], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"yash .soni@jayatma.com\")]), Storedge.Contact(fullName: \"Bhavesh Panchal\", 电话: \"\", 电子邮件: \"Bhavesh.panchal@jayatma.com\", imageDataAvailable: false,扩展:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符:\“564EB186-036C-437D-952D-A09A85A21027\”,namePrifix:\“\”,givenName:\“Bhavesh\”,middleName : \"\", familyName: \"Panchal\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle : \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\",birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth :假,日期:[],postalAddresses:[],urlAddresses:[],contactRelations:[],socialProfiles:[],instantMessageAddresses:[],phoneNumbers:[],emailAddresse s: [Storedge.Email(label: \"$!!$\", value: \"Bhavesh.panchal@jayatma.com\")]), Storage.Contact(fullName: \" Kayamuddin Ansari\",电话:\"7575801826\",电子邮件:\"kayamuddin.ansari@jayatma.com\",imageDataAvailable:false,扩展:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符: \"9D479A76-E092-4C9A-9BCC-418AB1DFC134\", namePrifix: \"\", givenName: \"Kayamuddin\", middleName: \"\", familyName: \"Ansari\", previousFamilyName: \"\ ", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\" , phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\",birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations : [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"7575801826\")], emailAddresse s: [Storedge.Email(label: \"$!!$\", value: \"kayamuddin.ansari@jayatma.com\")]), Storage.Contact(fullName: \" Manan Bhatt\",电话:\"7575801826\",电子邮件:\"manan.bhatt@jayatma.com\",imageDataAvailable:false,expanded:false,thumbnailImageData:0 字节,imageData:0 字节,contactType:0,标识符: \"0C1E052F-6636-4D47-979E-CFF2A66CF505\", namePrifix: \"\", givenName: \"Manan\", middleName: \"\", familyName: \"Bhatt\", previousFamilyName: \"\ ", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\" , phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\",birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations : [], socialProfiles: [], InstantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"7575801826\")], emailAddresses : [Storedge.Ema il(标签:\"$!!$\",值:\"manan.bhatt@jayatma.com\")])]"

【问题讨论】:

  • 可能有尝试设置非属性列表对象错误?看这里:stackoverflow.com/a/19720674
  • @StephanSchlecht 感谢您的快速回复,但我已经检查了这篇文章。

标签: cncontact userdefaults swift4.2


【解决方案1】:

由于您的联系人是可编码的,您可以使用 JSONEncoder/JSONDecoder 并执行以下操作:

if let json = try? JSONEncoder().encode(contact) {
    userDefs?.setValue(json, forKey: "contact");
    ...

然后再次检索联系人:

 if let loaded = userDefs?.value(forKey: "contact") as? Data {
     let contact2 = try? JSONDecoder().decode(Contact.self, from: loaded)
      ...

【讨论】:

  • 好吧,让我试试这个
  • 谢谢,@Stephan Schlecht 这很有魅力。我得到了我做错了什么的问题。
猜你喜欢
  • 2021-10-26
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2019-07-28
  • 1970-01-01
相关资源
最近更新 更多