写自动增量ID
我正在使用Swift的iOs程序,我正在使用Core Data,我试图找到如何获得自动增量ID,我发现这个:
但这里没有问题,所以我试着看看如何编写自动增量属性:我在名为“id”的.xcdatamodeld
文件中添加了一个新属性,我在Objective-C中找到了一个解决方案:
https://stackoverflow.com/a/22503259/5315947
但我不知道如何解析它到Swift2
我的代码:
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext let newDemande = NSEntityDescription.insertNewObjectForEntityForName("Demandes", inManagedObjectContext: context) newDemande.setValue(soapRequest.xmlString, forKey: "xml") newDemande.setValue(1, forKey: "statutenvoie") do { try context.save() } catch { print("erreur data") } do { let request = NSFetchRequest(entityName: "Demandes") let results = try context.executeFetchRequest(request) if results.count > 0 { for item in results as! [NSManagedObject]{ let xml = item.valueForKey("xml") let statutenvoie = item.valueForKey("statutenvoie") print(item.objectID) print(xml!, statutenvoie!) } } } catch { print("erreur data") }
UUID错误:
码:
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext let newDemande = NSEntityDescription.insertNewObjectForEntityForName("Demandes", inManagedObjectContext: context) newDemande.setValue(NSUUID().UUIDString, forKey: "id") newDemande.setValue(soapRequest.xmlString, forKey: "xml") newDemande.setValue(1, forKey: "statutenvoie") do { try context.save() } catch { print("erreur data") } do { let request = NSFetchRequest(entityName: "Demandes") let results = try context.executeFetchRequest(request) if results.count > 0 { for item in results as! [NSManagedObject]{ let id = item.valueForKey("id") let xml = item.valueForKey("xml") let statutenvoie = item.valueForKey("statutenvoie") // print(item.objectID) print(id!, xml!, statutenvoie!) } } } catch { print("erreur data") }
错误:
2016-01-11 16:33:18.921 ...[2694:108875] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "id"; desired type = NSNumber; given type = __NSCFString; value = 781EFF10-A9F1-4710-98C1-6D342B2EB480.' *** First throw call stack: ( 0 CoreFoundation 0x0000000110a2be65 __exceptionPreprocess + 165 1 libobjc.A.dylib 0x00000001132f8deb objc_exception_throw + 48 2 CoreData 0x00000001105c77b0 _PFManagedObject_coerceValueForKeyWithDescription + 2864 3 CoreData 0x000000011059f621 _sharedIMPL_setvfk_core + 177 4 ... 0x000000010ff690e5 _TFC7...29DemandeGratuiteViewController7ValiderfS0_FPSs9AnyObject_T_ + 4757 5 ... 0x000000010ff6aaa6 _TToFC7...29DemandeGratuiteViewController7ValiderfS0_FPSs9AnyObject_T_ + 54 6 UIKit 0x0000000112285e73 _UIGestureRecognizerSendTargetActions + 153 7 UIKit 0x00000001122824e5 _UIGestureRecognizerSendActions + 162 8 UIKit 0x00000001122804e2 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 843 9 UIKit 0x00000001122889a0 ___UIGestureRecognizerUpdate_block_invoke904 + 79 10 UIKit 0x000000011228883e _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 342 11 UIKit 0x0000000112276101 _UIGestureRecognizerUpdate + 2634 12 UIKit 0x0000000111e0df8a -[UIWindow _sendGesturesForEvent:] + 1137 13 UIKit 0x0000000111e0f1c0 -[UIWindow sendEvent:] + 849 14 UIKit 0x0000000111dbdb66 -[UIApplication sendEvent:] + 263 15 UIKit 0x0000000111d97d97 _UIApplicationHandleEventQueue + 6844 16 CoreFoundation 0x0000000110957a31 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 17 CoreFoundation 0x000000011094d95c __CFRunLoopDoSources0 + 556 18 CoreFoundation 0x000000011094ce13 __CFRunLoopRun + 867 19 CoreFoundation 0x000000011094c828 CFRunLoopRunSpecific + 488 20 GraphicsServices 0x0000000114c2dad2 GSEventRunModal + 161 21 UIKit 0x0000000111d9d610 UIApplicationMain + 171 22 ... 0x000000010ff352cd main + 109 23 libdyld.dylib 0x0000000113e0a92d start + 1 24 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
错误:
2016-01-12 09:13:03.726 ...[576:7439] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:file:///Users/informatiqueresponis/Library/Developer/CoreSimulator/Devices/314EFA4E-CC21-45A0-B3FD-FA486D52BB99/data/Containers/Data/Application/B0AB216F-D9B4-408D-ADB5-92BE2D333F62/Documents/SingleViewCoreData.sqlite options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=134100 "(null)" UserInfo={metadata={ NSPersistenceFrameworkVersion = 641; NSStoreModelVersionHashes = { Demandes = ; }; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "" ); NSStoreType = SQLite; NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0"; "_NSAutoVacuumLevel" = 2; }, reason=The model used to open the store is incompatible with the one used to create the store} with userInfo dictionary { metadata = { NSPersistenceFrameworkVersion = 641; NSStoreModelVersionHashes = { Demandes = ; }; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "" ); NSStoreType = SQLite; NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0"; "_NSAutoVacuumLevel" = 2; }; reason = "The model used to open the store is incompatible with the one used to create the store"; } 2016-01-12 09:13:03.730 ...[576:7439] Unresolved error Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo={NSLocalizedDescription=Failed to initialize the application's saved data, NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSUnderlyingError=0x7fded60cdae0 {Error Domain=NSCocoaErrorDomain Code=134100 "(null)" UserInfo={metadata={ NSPersistenceFrameworkVersion = 641; NSStoreModelVersionHashes = { Demandes = ; }; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "" ); NSStoreType = SQLite; NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0"; "_NSAutoVacuumLevel" = 2; }, reason=The model used to open the store is incompatible with the one used to create the store}}}, [NSLocalizedDescription: Failed to initialize the application's saved data, NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=134100 "(null)" UserInfo={metadata={ NSPersistenceFrameworkVersion = 641; NSStoreModelVersionHashes = { Demandes = ; }; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "" ); NSStoreType = SQLite; NSStoreUUID = "7C53DEAF-C47E-446B-913E-060946C728B0"; "_NSAutoVacuumLevel" = 2; }, reason=The model used to open the store is incompatible with the one used to create the store}] (lldb)
你在评论中给出的例子仍然令人困惑。 我的回答是基于我的理解,你想要一个自动增加字段 – id
,当你下次插入一个新条目时。
如果你有两个字段,即xmlString
和id
。 然后,首先你每次都是一个使用SortDescriptor
和setFetchLimit = 1
的获取请求。 如果结果为空,则插入id = 1
的新条目。 否则,插入id = oldId + 1
的新条目。
我故意不提供任何代码,因为我不确定你真正想要的是什么。
顺便说一下,你最好使用自定义模型,即由XCode
生成的NSManagedObject
,而不是当前的newDemande.setValue(value, forKey: "key")
编辑
示例代码提供:
// Initialize Fetch Request let fetchRequest = NSFetchRequest(entityName: "Demandes") // Sort Descriptor var idDescriptor: NSSortDescriptor = NSSortDescriptor(key: "id", ascending: false) fetchRequest.sortDescriptors = [idDescriptor] // Note this is a array, you can put multiple sort conditions if you want // Set limit fetchRequest.fetchLimit = 1 var newId = 0; // Default to 0, so that you can check if do catch block went wrong later do { let results = try self.managedObjectContext.executeFetchRequest(fetchRequest) //Compute the id if(results.count == 1) newId = results[0].id + 1 // slightly odd notation here, .id can be used if you use custom model. or you can use .valueForKey("id") else newId = 1 } catch { let fetchError = error as NSError print(fetchError) } // Do the new insert afterwards
我认为你发送的是一个字符串值(781EFF10-A9F1-4710-98C1-6D342B2EB480),核心数据需要一个NSNumber(Int)。 显然,781EFF10-A9F1-4710-98C1-6D342B2EB480不是数字。
核心数据始终将Int(Doubles,Float等)值存储为NSNumber,例如:
let intValue let intValueInNSNumber = NSNumber(int: intValue)
区别在于intValue(Int)是基本类型,而NSNumber是一个对象。
属性“id”的类型是什么?
因为,如果属性的类型为“Int”,则必须将其更改为“String”,它应该可以工作。