I'm working on a iOs program in Swift, I'm using Core Data, I tried to found how to have a auto increment id, I found this:
But no issues here, so I tried to see how to write a self auto increment attribute:
I added a new attribute in my .xcdatamodeld file named "id", I found a solution in Objective-C:
https://stackoverflow.com/a/22503259/5315947
But I don't know how to parse it into Swift2
My code:
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 error:
code:
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")
}
error:
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)
Error:
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 = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
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 = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
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 = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
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 = <e6fa8ed7 47097048 95c90274 cbc26ea7 decd6ea3 12e0df98 cd0d3cec da84d5ff>;
};
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)
Still confusing with the example you gave in the comment. My answer is based on my understand that you want an auto increase field - id, when next time you insert a new entry.
If you have two fields, i.e. xmlString & id. Then first you do everytime is a fetch request with SortDescriptor and setFetchLimit = 1. If the result is empty, you insert a new entry with id = 1. Otherwise, insert a new entry with id = oldId + 1.
I intentionally doesn't provide any code, because I'm not sure what you really want.
BTW, you'd better to use custom model, i.e. NSManagedObject generated by XCode, rather than the current newDemande.setValue(value, forKey: "key")
EDIT
Example code provided:
// 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
I think you are sending a string value (781EFF10-A9F1-4710-98C1-6D342B2EB480) and core data is expecting an NSNumber (Int). Obviously, 781EFF10-A9F1-4710-98C1-6D342B2EB480 is not a number.
Core data always stores Int (Doubles, Float, etc...) values as NSNumber, for example:
let intValue
let intValueInNSNumber = NSNumber(int: intValue)
The difference is that intValue (Int) is a primitive type, while NSNumber is an object.
What's the type for the attribute "id"?
Because, if the attribute is of type "Int" you will have to change it to "String" and it should work.
Related
I have this error after saving entites (DictionaryMarketSubcategoryEntity), than saving them again.
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<DictionaryMarketSubcategoryEntity 0x60000269e2b0> setValue:forUndefinedKey:]: the entity DictionaryMarketSubcategoryEntity is not key value coding-compliant for the key "(null)".'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff8004278cb __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80004dba3 objc_exception_throw + 48
2 CoreFoundation 0x00007ff80042753d -[NSException init] + 0
3 CoreData 0x00007ff8049b8a02 -[NSMergePolicy _mergeToManyUnionRelationshipsForObject:andObject:] + 945
4 CoreData 0x00007ff8049bcf29 -[NSMergePolicy resolveConstraintConflicts:error:] + 5412
5 CoreData 0x00007ff8049bb99a -[NSMergePolicy resolveConflicts:error:] + 210
6 CoreData 0x00007ff80497a534 -[NSManagedObjectContext save:] + 3215
7 FCDev 0x0000000101624e04 $s5FCDev13CoreDataStackC20saveContextIfChangedyyF + 1524
8 FCDev 0x0000000101573f8b $s5FCDev36CoreDataStorageServiceImplementationC5writeyyF + 43
9 FCDev 0x0000000101575710 $s5FCDev36CoreDataStorageServiceImplementationCAA0dE0A2aDP5writeyyFTW + 16
10 FCDev 0x0000000100a02291
Here is entity (DictionaryMarketSubcategoryEntity) that I save. It has child subcategories (DictionaryMarketSubcategoryEntity). If I comment and remove child, then everything OK. It seems that when I save array of DictionaryMarketCategoryEntity it save child entities (DictionaryMarketSubcategoryEntity) and after resaving them, the merge policy give a crash. Why?
Here is code of init:
extension DictionaryMarketCategoryEntity: JSONInitializable {
convenience init(json: JSON) {
self.init(context: AppInstances.shared.storage.context)
self.backgroundColor = json["backgroundColor"].stringValue
self.backgroundImagePath = json["backgroundImage"].stringValue
self.descriptionText = json["description"].stringValue
self.icon = json["icon"].stringValue
self.id = json["id"].stringValue
self.imagePath = json["image"].stringValue
self.parent = json["parent"].stringValue
self.span = json["span"].int16Value
self.title = json["title"].stringValue
self.type = json["type"].stringValue
let childrenJson = json["children"].arrayValue
let childrenEntities = childrenJson.map { DictionaryMarketSubcategoryEntity(json: $0) }
let childrenSet = NSSet(array: childrenEntities)
addToChildren(childrenSet)
}
}
extension DictionaryMarketSubcategoryEntity {
convenience init(json: JSON) {
self.init(context: AppInstances.shared.storage.context)
self.id = json["id"].stringValue
self.title = json["title"].stringValue
self.descriptionText = json["description"].stringValue
self.imagePath = json["image"].stringValue
self.backgroundImagePath = json["backgroundImage"].stringValue
self.backgroundColor = json["backgroundColor"].stringValue
self.icon = json["icon"].stringValue
self.parent = json["parent"].stringValue
self.span = json["span"].int16Value
self.type = json["type"].stringValue
}
}
I've added the parent relationship in subcategory. Then in main entity using addToChildrenEntities - the autogenerated by xcode function. After that the error has gone. It's not because the JSON. It seems that core data fail to merge if child entity (subcategory) doesn't know what is his parent entity.
I’m new to iOS (Swift) development, and I’ve been tinkering with this all week. I am trying to update only the city of the postal addresses of a contact from iOS Contacts, and leave the rest of the postal address (street, ZIP code, etc.) intact. I figured I could just get a mutable copy of the contact.postalAddress using postalAddress.mutableCopy(), and then write to mutableCopy.city = “New City”. However, when I try this I get a -[CNLabeledValue mutableCopyWithZone:]: unrecognized selector sent to instance error. My current solution is to create a new address filled with values from the old address, but it seems there should be a better way (like copying the old address and just changing the city, like I’m trying to do). Is there something I’m missing? Thanks!
So, what I want to work:
func updateContact(contact: CNContact) -> BooleanLiteralType{
var success = false
let store = CNContactStore()
do {
let updContact = contact.mutableCopy() as! CNMutableContact
var addrArray = [CNLabeledValue<CNPostalAddress>]()
for postAddress in updContact.postalAddresses{
let curLabel = postAddress.label
var address = postAddress.mutableCopy() as! CNMutablePostalAddress
address.city = "Cityville"
let curAddrLabeledVal = CNLabeledValue<CNPostalAddress>(label:curLabel, value:address)
addrArray.append(curAddrLabeledVal)
}
updContact.postalAddresses = addrArray
let req = CNSaveRequest()
req.update(updContact)
try store.execute(req)
success = true
}
catch let err{
print(err)
}
return success
}
This results in the following exception:
2020-05-26 00:06:19.537517+0200 My App[78089:4168944] -[CNLabeledValue mutableCopyWithZone:]: unrecognized selector sent to instance 0x600001388b80
2020-05-26 00:06:19.545537+0200 My App[78089:4168944] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CNLabeledValue mutableCopyWithZone:]: unrecognized selector sent to instance 0x600001388b80'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23e3cf0e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff50ba89b2 objc_exception_throw + 48
2 CoreFoundation 0x00007fff23e5dc34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3 CoreFoundation 0x00007fff23e4190c ___forwarding___ + 1436
4 CoreFoundation 0x00007fff23e43bf8 _CF_forwarding_prep_0 + 120
5 My App 0x00000001015b4898 $s12My_App13updateContact7contactSbSo9CNContactC_tF + 1048
6 My App 0x00000001015bf3f1 $s12My_App11ContentViewV4bodyQrvg7SwiftUI05TupleD0VyAE0D0PAEE7opacityyQrSdFQOyAiEE5frame5width6height9alignmentQr12CoreGraphics7CGFloatVSg_ArE9AlignmentVtFQOyAA11ProgressBarV_Qo__Qo__AE010NavigationD0VyAiEE010navigationS5Items7leading8trailingQrqd___qd_0_tAeHRd__AeHRd_0_r0_lFQOyAiEE0uS5TitleyQrAE4TextVFQOyAE4ListVys5NeverOAE7ForEachVySaySo9CNContactCGSSAE6HStackVyAE0T4LinkVyAA10ContactRowVAA13ContactDetailVGGGG_Qo__AE6ButtonVyA4_GA29_Qo_GtGyXEfU_A30_yXEfU_yycfU2_yycfU_ + 465
7 My App 0x00000001015bf8f0 $sIeg_IeyB_TR + 48
8 libdispatch.dylib 0x0000000101877f11 _dispatch_call_block_and_release + 12
9 libdispatch.dylib 0x0000000101878e8e _dispatch_client_callout + 8
10 libdispatch.dylib 0x000000010187b2d8 _dispatch_queue_override_invoke + 1022
11 libdispatch.dylib 0x000000010188a399 _dispatch_root_queue_drain + 351
12 libdispatch.dylib 0x000000010188aca6 _dispatch_worker_thread2 + 135
13 libsystem_pthread.dylib 0x00007fff51c089f7 _pthread_wqthread + 220
14 libsystem_pthread.dylib 0x00007fff51c07b77 start_wqthread + 15
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
This is the solution that works, but as you can see it’s not really what I want as it requires me to define all postalAddress attributes:
func updateContact(contact: CNContact) -> BooleanLiteralType{
var success = false
let store = CNContactStore()
do {
let updContact = contact.mutableCopy() as! CNMutableContact
var addrArray = [CNLabeledValue<CNPostalAddress>]()
for postAddress in updContact.postalAddresses{
let curLabel = postAddress.label
let address = CNMutablePostalAddress()
address.street = postAddress.value.street
address.city = "Cityville"
address.postalCode = postAddress.value.postalCode
address.state = postAddress.value.state
address.country = postAddress.value.country
address.isoCountryCode = postAddress.value.isoCountryCode
address.subAdministrativeArea = postAddress.value.subAdministrativeArea
address.subLocality = postAddress.value.subLocality
let curAddrLabeledVal = CNLabeledValue<CNPostalAddress>(label:curLabel, value:address)
addrArray.append(curAddrLabeledVal)
}
updContact.postalAddresses = addrArray
let req = CNSaveRequest()
req.update(updContact)
try store.execute(req)
success = true
}
catch let err{
print(err)
}
return success
}
Any help is much appreciated!
I am getting a crash related to a core data relationship which is to-many
nueva marca -----><Autos.Marca: 0x7fac604d3250> (entity: Marca; id:
0x7fac604d3300
<x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672> ; data: {
modelos = (
);
nombre = NIKE; })
Nuevo modelo:::::::: <Autos.Modelo: 0x7fac604d6df0> (entity: Modelo;
id: 0x7fac604d6e50
<x-coredata:///Modelo/tB1CE1C53-077E-4402-8E3A-E6C6F147B4673> ; data:
{
marca = "0x7fac604d3300 <x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672>";
nombre = "AIRFORCE 1"; }) arreglo Relationship 'modelos' on managed object (0x7fac604d3250) <Autos.Marca: 0x7fac604d3250> (entity:
Marca; id: 0x7fac604d3300
<x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672> ; data: {
modelos = (
"0x7fac604d6e50 <x-coredata:///Modelo/tB1CE1C53-077E-4402-8E3A-E6C6F147B4673>"
);
nombre = NIKE; }) with objects {(
<Autos.Modelo: 0x7fac604d6df0> (entity: Modelo; id: 0x7fac604d6e50> <x-coredata:///Modelo/tB1CE1C53-077E-4402-8E3A-E6C6F147B4673> ; data:
{
marca = "0x7fac604d3300 <x-coredata:///Marca/tB1CE1C53-077E-4402-8E3A-E6C6F147B4672>";
nombre = "AIRFORCE 1"; }) )} Nuevo Marca <Autos.Marca: 0x7fac604d3250> (entity: Marca; id: 0xd000000000080000
<x-coredata://D8BC4DF2-5A4A-4D3D-A10D-91FE28DABA30/Marca/p2> ; data: {
modelos = (
"0xd000000000080002 <x-coredata://D8BC4DF2-5A4A-4D3D-A10D-91FE28DABA30/Modelo/p2>"
);
nombre = NIKE; }) 2016-05-03 11:21:22.778 Autos[745:17150] *** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'to-many key not allowed here'
*** First throw call stack: ( 0 CoreFoundation 0x000000010bbc7d85 __exceptionPreprocess + 165 1 libobjc.A.dylib
0x000000010d96bdeb objc_exception_throw + 48 2 CoreData
0x000000010b81efff -[NSSQLGenerator newSQLStatementForRequest:ignoreInheritance:countOnly:nestingLevel:nestIsWhereScoped:]
+ 1583 3 CoreData 0x000000010b7117e3 -[NSSQLGenerator newSQLStatementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:nestIsWhereScoped:]
+ 35 4 CoreData 0x000000010b8047b8 -[NSSQLAdapter _statementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:]
+ 344 5 CoreData 0x000000010b71167c -[NSSQLAdapter _newSelectStatementWithFetchRequest:ignoreInheritance:]
+ 316 6 CoreData 0x000000010b7112f6 -[NSSQLCore newRowsForFetchPlan:]
+ 118 7 CoreData 0x000000010b710bac -[NSSQLCore objectsForFetchRequest:inContext:]
+ 524 8 CoreData 0x000000010b710549 -[NSSQLCore executeRequest:withContext:error:]
+ 377 9 CoreData 0x000000010b7f5eaf __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke
+ 3311 10 CoreData 0x000000010b7ff4dd gutsOfBlockToNSPersistentStoreCoordinatorPerform
+ 189 11 libdispatch.dylib 0x000000010e4043eb _dispatch_client_callout
+ 8 12 libdispatch.dylib 0x000000010e3e8ef5 _dispatch_barrier_sync_f_invoke
+ 393 13 CoreData 0x000000010b7f05d5 _perform
+ 197 14 CoreData 0x000000010b7101b4 -[NSPersistentStoreCoordinator
executeRequest:withContext:error:]
+ 500 15 CoreData 0x000000010b70e973 -[NSManagedObjectContext executeFetchRequest:error:]
+ 579 16 CoreData 0x000000010b7c65f5 -[NSManagedObjectContext executeRequest:error:]
+ 421 17 Autos 0x000000010b652db9 _TFC5Autos14ViewController11viewDidLoadfT_T_
+ 3929 18 Autos 0x000000010b6531f2 _TToFC5Autos14ViewController11viewDidLoadfT_T_
+ 34 19 UIKit 0x000000010c58a984 -[UIViewController loadViewIfRequired]
+ 1198 20 UIKit 0x000000010c58acd3 -[UIViewController view]
...
My view controller code is:
let appDelegado:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let contexto:NSManagedObjectContext = appDelegado.managedObjectContext
let entidadMarca = "Marca"
let entidadModelo = "Modelo"
let modeloNike = "AIRFORCE 1"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//Conusltando Base de datos
let newMarca = NSEntityDescription.insertNewObjectForEntityForName(entidadMarca, inManagedObjectContext:contexto)
newMarca.setValue("NIKE", forKey: "nombre")
print("nueva marca ----->\(newMarca) \n")
//objeto modelo
let newModelo = NSEntityDescription.insertNewObjectForEntityForName(entidadModelo, inManagedObjectContext:contexto)
newModelo.setValue("AIRFORCE 1", forKey: "nombre")
let entytiModelo = NSEntityDescription.entityForName(entidadMarca, inManagedObjectContext:contexto)
let objArray = newMarca.mutableSetValueForKey("modelos")
objArray.addObject(newModelo)
print("Nuevo modelo:::::::: \(newModelo)")
print("arreglo \(objArray)")
saveInBD()
print("Nuevo Marca \(newMarca)")
let entityMarca = NSEntityDescription.entityForName(entidadMarca, inManagedObjectContext:contexto)
let oderBy = NSSortDescriptor(key: "nombre", ascending: true)
let consulta = NSFetchRequest(entityName:entidadMarca )
consulta.sortDescriptors = [oderBy]
let predicate = NSPredicate(format: "modelos = %#",modeloNike )
consulta.entity = entityMarca
consulta.predicate = predicate
if let resultado = try?contexto.executeRequest(consulta){
print("Resultado:::::::--->\(resultado)")
}else{
print("No hay Valores")
}
}
func saveInBD() {
do {
try contexto.save() // Il metodo .save() dell'NSManagedObjectContext svolge questo compito.
} catch let error {
print((error as! NSErrorPointer).debugDescription)
}
}
}
It looks like:
You are fetching the entity Marca
Your predicate for this fetch is NSPredicate(format: "modelos = %#",modeloNike)
modelos is a to-many relationship, which will be represented as a set
modeloNike is a String
So you're asking Core Data to compare two things which are not of the same type, comparing a set to a string. There's your problem.
When my code tries to download the series from the API, it randomly crashes with this error message:
(entity: Series; id:
0x7b181002016-04-04 14:01:33.868 Postzegel Catalogus[1816:39059]
CoreData: error: Serious application error. Exception was caught
during Core Data change processing. This is usually a bug within an
observer of NSManagedObjectContextObjectsDidChangeNotification.
-[NSCFSet addObject:]: attempt to insert nil with userInfo (null) 0 (entity: Series; id:
0x7b00c450
;
2016-04-04 14:01:33.871 Postzegel Catalogus[1816:39059] *** Terminating app due
to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFSet addObject:]: attempt to insert nil'
*** First throw call stack: ( 0 CoreFoundation 0x0083d494 __exceptionPreprocess + 180 1 libobjc.A.dylib
0x02551e02 objc_exception_throw + 50 2 CoreFoundation
0x0083d3bd +[NSException raise:format:] + 141 3 CoreFoundation
0x0070c959 -[__NSCFSet addObject:] + 185 4 CoreData
0x0038a010 -[NSManagedObjectContext(_NSInternalChangeProcessing)
_processPendingInsertions:withDeletions:withUpdates:] + 560 5 CoreData 0x003846da
-[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 2410 6 CoreData 0x00383d56 -[NSManagedObjectContext processPendingChanges] + 54 7
CoreData 0x003ae5e4
-[NSManagedObjectContext(_NestedContextSupport) _parentProcessSaveRequest:inContext:error:] + 116 8 CoreData 0x00433bec __82-[NSManagedObjectContext(_NestedContextSupport)
executeRequest:withContext:error:]_block_invoke + 412 9 CoreData
0x003a924c internalBlockToNSManagedObjectContextPerform + 76 10
libdispatch.dylib 0x03c8f9cd
_dispatch_client_callout + 14 11 libdispatch.dylib 0x03c76d90 _dispatch_barrier_sync_f_slow_invoke + 133 12
libdispatch.dylib 0x03c8f9cd
_dispatch_client_callout + 14 13 libdispatch.dylib 0x03c74f7c _dispatch_main_queue_callback_4CF + 910 14 CoreFoundation
0x007871be __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 14 15
CoreFoundation 0x00745434 __CFRunLoopRun + 2356
16 CoreFoundation 0x00744846
CFRunLoopRunSpecific + 470 17 CoreFoundation
0x0074465b CFRunLoopRunInMode + 123 18 GraphicsServices
0x07a8d664 GSEventRunModal + 192 19 GraphicsServices
0x07a8d4a1 GSEventRun + 104 20 UIKit
0x0102beb9 UIApplicationMain + 160 21 Postzegel Catalogus
0x000f63b1 main + 145 22 libdyld.dylib
0x03cb9a25 start + 1 ) (entity: Series; id: 0x7b25bc40
;
And I just don't know why? I used a private Managed Context Option so that using a . I even set the fields in my .xcdatamodeld to optional. So it shouldn't be a problem it it is nil? And it just keeps crashing randomly, not even at the same object. How can I fix this?
I included my code in the hope that might help you. I have removed my API key, so you won't be able to try it out. If you have any other comment on my code please tell me, I'm new to Core Data and Alamofire so I have the tenancy to make 'spaghetti code'.
Thanks in advance
import Foundation
import CoreData
import Alamofire
import SwiftyJSON
//CoreData Init
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext
let queue = dispatch_queue_create("com.GJ-Computers.Postzegel-Catalogus.responseJSON-Manager", DISPATCH_QUEUE_CONCURRENT)
//Colnect API
let LANG: String = NSLocale.preferredLanguages()[0].substringToIndex(NSLocale.preferredLanguages()[0].startIndex.advancedBy(2))
let DATE = NSCalendar.currentCalendar().component([.Day, .Month, .Year], fromDate: NSDate())
let API_KEY: String = "----" //Private API KEY
let CAT_STAMPS: String = ("cat/stamps/")
var BASE_URL: String{
return ("http://api.colnect.net/" + LANG + "/api/" + API_KEY + "/")
}
//Ghetto Delegate
var didGetCountires: Bool = false
var didGetYears: Bool = false
var didGetSeries: Bool = false
//MARK: - First Time setup Database
func setupDatabase(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){
getYears() //Download Years per country from database
}
}
//get Series
func getSeries(){
//Retrieve Countries from Coredata
let countryFetchRequest = NSFetchRequest(entityName: "Countries")
var results: [Countries]?
do {
results = try managedContext.executeFetchRequest(countryFetchRequest) as? [Countries]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
let resultCount = results!.count
var completedRequestCount: Int = 0
var requestedRequests = 0
for result in results!{
let countryID = result.countryID
Alamofire.request(.GET, (BASE_URL + "series/"+CAT_STAMPS+"producer/\(countryID)")).responseJSON(queue: queue, completionHandler:{ response in
if let json = response.result.value{
let privateMOC = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateMOC.parentContext = managedContext
let rawData = JSON(json)
for data in rawData {
//Setup let
let seriesID = Int(data.1.array![0].string!)
let seriesName = data.1.array![1].string
let itemCount = Int(data.1.array![2].string!)
if seriesID != 0 && itemCount != 0 && seriesName != nil{
privateMOC.performBlock{
let series = NSEntityDescription.insertNewObjectForEntityForName("Series", inManagedObjectContext: managedContext) as! Series
series.countryID = countryID
series.seriesID = seriesID
series.seriesName = seriesName
series.itemCount = itemCount
print(completedRequestCount)
do {
try privateMOC.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
}else{
print("ERROR")
}
}
}
completedRequestCount += 1
print(completedRequestCount)
})
requestedRequests += 1
if(requestedRequests == resultCount){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)){
while(true){
if(completedRequestCount == resultCount){
didGetSeries = true
sleep(3)
print("DEBUG - Series Done")
break
}
}
}
}
}
}
Actually, the reason, using private MOC solved your problem is because you are performing the operation in the background thread, and when you do coredata operation in the background thread you have to ensure that
Managed object contexts are bound to the thread (queue) that they are
associated with upon initialization
Managed objects retrieved from a context are bound to the same queue
that the context is bound to
FYI not because of ("I made a private MOC, but when you make one you have to consistently add it in the code otherwise it won't work. I forgot to replace managedContext with privateMOC")
Solved it Myself. I made a private MOC, but when you make one you have to consistently add it in the code otherwise it won't work. I forgot to replace managedContext with privateMOC. My bad
let series = NSEntityDescription.insertNewObjectForEntityForName("Series", inManagedObjectContext: managedContext) as! Series
should be
let series = NSEntityDescription.insertNewObjectForEntityForName("Series", inManagedObjectContext: privateMOC) as! Series
I am reading safari's Bookmarks.plist and storing it in an NSDictionary then trying to convert the NSDictionary into JSON
Problem
Bookmarks data is getting into dictionary but when I am converting the data into JSON the application is crashing.
NSString* path = #"path of the plist file";
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:path];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:plistDict
options:NSJSONWritingPrettyPrinted error:&error];
NSString* result = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
Reason
The NSDictonary made of the Plist file contains some fields that are the type of NSData. Is there a way to convert all NSData fields to Base64 string in order clean the NSDictionary? Note that it is not possible to be aware of what fields and how many fields are type of NSData beforehand.
ErrorLog
2016-04-12 14:44:13.560 plistTOjosn[4228:68289] An uncaught exception was raised
2016-04-12 14:44:13.560 plistTOjosn[4228:68289] Invalid type in JSON write (__NSCFData)
2016-04-12 14:44:13.561 plistTOjosn[4228:68289] (
0 CoreFoundation 0x00007fff92d9b03c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff914e176e objc_exception_throw + 43
2 CoreFoundation 0x00007fff92d9aeed +[NSException raise:format:] + 205
3 Foundation 0x00007fff91174b9a _writeJSONValue + 715
4 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
5 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
6 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
7 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
8 Foundation 0x00007fff91175b1f _writeJSONObject + 439
9 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
10 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
11 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
12 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
13 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
14 Foundation 0x00007fff91175b1f _writeJSONObject + 439
15 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
16 Foundation 0x00007fff9117489a -[_NSJSONWriter dataWithRootObject:options:error:] + 137
17 Foundation 0x00007fff91174765 +[NSJSONSerialization dataWithJSONObject:options:error:] + 345
18 Utilities 0x00000001000c7d0b -[BrowserJunkUtilities readPlistFileFromSafariProfiles:] + 331
19 Utilities 0x00000001000c7e4b -[BrowserJunkUtilities safariBookmarksJson] + 59
20 Utilities 0x00000001000bbd5c -[BrowserJunkUtilities LogInBigData] + 252
21 Utilities 0x00000001000c1af2 -[BrowserJunkUtilities init] + 5970
22 plistTOjosn 0x00000001000299e5 -[DashBoardView init] + 261
23 plistTOjosn 0x0000000100016e45 -[AppController changeViewController:RunFix:] + 757
24 plistTOjosn 0x0000000100018fe5 -[AppController showIntroView:tag:] + 181
25 plistTOjosn 0x0000000100016a7f -[AppController awakeFromNib] + 1103
26 CoreFoundation 0x00007fff92ca7bdf -[NSSet makeObjectsPerformSelector:] + 223
27 AppKit 0x00007fff9329e03d -[NSIBObjectData nibInstantiateWithOwner:options:topLevelObjects:] + 1216
28 AppKit 0x00007fff9327d0e5 loadNib + 384
29 AppKit 0x00007fff9327c60b +[NSBundle(NSNibLoading) _loadNibFile:nameTable:options:withZone:ownerBundle:] + 313
30 AppKit 0x00007fff9327c3c7 -[NSBundle(NSNibLoading) loadNibNamed:owner:topLevelObjects:] + 201
31 AppKit 0x00007fff9327c193 +[NSBundle(NSNibLoading) loadNibNamed:owner:] + 344
32 AppKit 0x00007fff93274d79 NSApplicationMain + 605
33 plistTOjosn 0x0000000100007542 main + 34
34 plistTOjosn 0x00000001000016d4 start + 52
35 ??? 0x0000000000000003 0x0 + 3
)
2016-04-12 14:44:13.690 plistTOjosn[4228:68289] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSCFData)'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff92d9b03c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff914e176e objc_exception_throw + 43
2 CoreFoundation 0x00007fff92d9aeed +[NSException raise:format:] + 205
3 Foundation 0x00007fff91174b9a _writeJSONValue + 715
4 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
5 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
6 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
7 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
8 Foundation 0x00007fff91175b1f _writeJSONObject + 439
9 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
10 Foundation 0x00007fff91175cef ___writeJSONObject_block_invoke + 220
11 CoreFoundation 0x00007fff92d9a65c ____NSDictionaryEnumerate_block_invoke439 + 28
12 CoreFoundation 0x00007fff92c7b0b0 CFBasicHashApply + 128
13 CoreFoundation 0x00007fff92cbc118 __NSDictionaryEnumerate + 664
14 Foundation 0x00007fff91175b1f _writeJSONObject + 439
15 Foundation 0x00007fff91174ab6 _writeJSONValue + 487
16 Foundation 0x00007fff9117489a -[_NSJSONWriter dataWithRootObject:options:error:] + 137
17 Foundation 0x00007fff91174765 +[NSJSONSerialization dataWithJSONObject:options:error:] + 345
18 Utilities 0x00000001000c7d0b -[BrowserJunkUtilities readPlistFileFromSafariProfiles:] + 331
19 Utilities 0x00000001000c7e4b -[BrowserJunkUtilities safariBookmarksJson] + 59
20 Utilities 0x00000001000bbd5c -[BrowserJunkUtilities LogInBigData] + 252
21 Utilities 0x00000001000c1af2 -[BrowserJunkUtilities init] + 5970
22 plistTOjosn 0x00000001000299e5 -[DashBoardView init] + 261
23 plistTOjosn 0x0000000100016e45 -[AppController changeViewController:RunFix:] + 757
24 plistTOjosn 0x0000000100018fe5 -[AppController showIntroView:tag:] + 181
25 plistTOjosn 0x0000000100016a7f -[AppController awakeFromNib] + 1103
26 CoreFoundation 0x00007fff92ca7bdf -[NSSet makeObjectsPerformSelector:] + 223
27 AppKit 0x00007fff9329e03d -[NSIBObjectData nibInstantiateWithOwner:options:topLevelObjects:] + 1216
28 AppKit 0x00007fff9327d0e5 loadNib + 384
29 AppKit 0x00007fff9327c60b +[NSBundle(NSNibLoading) _loadNibFile:nameTable:options:withZone:ownerBundle:] + 313
30 AppKit 0x00007fff9327c3c7 -[NSBundle(NSNibLoadin
g) loadNibNamed:owner:topLevelObjects:] + 201
31 AppKit 0x00007fff9327c193 +[NSBundle(NSNibLoading) loadNibNamed:owner:] + 344
32 AppKit 0x00007fff93274d79 NSApplicationMain + 605
33 plistTOjosn 0x0000000100007542 main + 34
34 plistTOjosn 0x00000001000016d4 start + 52
35 ??? 0x0000000000000003 0x0 + 3
)
libc++abi.dylib: terminating with uncaught exception of type NSException
PLIST DATA
{
Children = (
{
Title = History;
WebBookmarkIdentifier = History;
WebBookmarkType = WebBookmarkTypeProxy;
WebBookmarkUUID = "019DBF83-1882-46AA-A8A7-669CCD3D5AB8";
},
{
Children = (
{
Sync = {
Key = "\"C=32#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/63582BD8-0400-40C4-9CA7-8942391957B8.xbel";
};
URIDictionary = {
title = "vikas Technologies Pvt. Ltd Mail";
};
URLString = "https://mail.google.com/mail/u/0/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "AFDCB7C0-10CE-4273-BDF8-E2FC40D83A3A";
},
{
Sync = {
Key = "\"C=6#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/474F816C-BB3E-4F42-89B4-666F5E323840.xbel";
};
URIDictionary = {
title = Apple;
};
URLString = "https://www.apple.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "4468D8F5-6A99-4B0A-85AD-E1E49B58546D";
},
{
Sync = {
Key = "\"C=8#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/89401E9C-92BB-4935-91D1-F968FD90239B.xbel";
};
URIDictionary = {
title = iCloud;
};
URLString = "https://www.icloud.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "2E4E8D77-D2C4-4B79-A563-5FF5FED0D553";
},
{
Sync = {
Key = "\"C=10#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/6B14FBB9-DA11-4F5B-BF85-4E997D73C720.xbel";
};
URIDictionary = {
title = Yahoo;
};
URLString = "https://www.yahoo.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "9CFD581F-2404-4BDF-8795-5D4DCC9A7CF0";
},
{
Sync = {
Key = "\"C=12#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/0F0130B7-2F0C-4BD5-9173-E91C210F845C.xbel";
};
URIDictionary = {
title = Bing;
};
URLString = "https://www.bing.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "89FEEC32-AC16-4A80-8875-68BE4A191862";
},
{
Sync = {
Key = "\"C=14#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/9554C3E5-61CD-40BE-BFB2-7FBEB22807C0.xbel";
};
URIDictionary = {
title = Google;
};
URLString = "https://www.google.com/?client=safari&channel=mac_bm";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "5A013EF2-E017-41B3-8FAE-2DA718D35AC5";
},
{
Sync = {
Key = "\"C=16#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/56EA5315-E1B1-430B-A018-7326A247ECAA.xbel";
};
URIDictionary = {
title = Wikipedia;
};
URLString = "https://www.wikipedia.org/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "49CE5DC7-6ABD-4876-95E4-0C7A007DED0D";
},
{
Sync = {
Key = "\"C=18#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/FDF4AD0D-FD33-4EE2-9097-19CA5046AFB7.xbel";
};
URIDictionary = {
title = Facebook;
};
URLString = "https://www.facebook.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "530A47C6-D116-4081-9BED-3C469C7C7697";
},
{
Sync = {
Key = "\"C=20#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/3E61C9CF-7646-4475-AC89-FB157DA50181.xbel";
};
URIDictionary = {
title = Twitter;
};
URLString = "https://twitter.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "D3893EF3-A885-41F6-A128-BBAC37A2033B";
},
{
Sync = {
Key = "\"C=22#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/C8801D19-7A76-4290-8950-5DA9385F3415.xbel";
};
URIDictionary = {
title = LinkedIn;
};
URLString = "https://www.linkedin.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "47F6045D-4F9A-4856-916A-07CB8889B7E2";
},
{
Sync = {
Key = "\"C=24#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/DF10E9C3-01FA-4EC6-ADE2-4A0B1FECD9EF.xbel";
};
URIDictionary = {
title = "The Weather Channel";
};
URLString = "http://www.weather.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "0DDD3778-437A-4FAE-8529-D389A5122758";
},
{
Sync = {
Key = "\"C=26#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/79C2C180-430C-4092-A4CF-D2B8F4551B1E.xbel";
};
URIDictionary = {
title = Yelp;
};
URLString = "http://www.yelp.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "2FD1AB60-B3A0-44D5-A20D-68CF51A40584";
},
{
Sync = {
Key = "\"C=28#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/63EDC45D-3138-41CF-A617-4178097656F0.xbel";
};
URIDictionary = {
title = TripAdvisor;
};
URLString = "http://www.tripadvisor.com/";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "A6DA8288-409E-4B03-84E4-ACEF9F2B624C";
},
{
Sync = {
Key = "\"C=30#U=19016305-56c9-437c-95f4-93521bad2be8\"";
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/40F8D2AF-4F2E-44BE-8250-41E1C7C0F1D9.xbel";
};
URIDictionary = {
title = "ADplus.aspx";
};
URLString = "http://dev.etelmar.net/ADEV_ADplus3-01/ADplus.aspx";
WebBookmarkType = WebBookmarkTypeLeaf;
WebBookmarkUUID = "C5D3ADD4-DB17-421D-BAF5-04927F713BCE";
}
);
Sync = {
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/2A662FEA-35F9-44C5-87B9-8DDEBE0E4912/";
};
Title = BookmarksBar;
WebBookmarkType = WebBookmarkTypeList;
WebBookmarkUUID = "E2EC6281-F0F9-41FA-9C2C-2DC8745F547A";
},
{
Sync = {
ServerID = "https://bnslvks%40icloud.com#p35-bookmarks.icloud.com/8402630368/bookmarks/C81C19F2-E6A6-46C7-9836-DC58A02B46AB/";
};
Title = BookmarksMenu;
WebBookmarkType = WebBookmarkTypeList;
WebBookmarkUUID = "06621BC7-DAA3-4225-8BCB-A65A8E0D0916";
}
);
Sync = {
ServerData = <62706c69 73743030 de010203 04050607 08090a0b 0c0d0e0f 10111213 14151624 25303120 20545054 61675443 54616757 50757368 4b65795d 426f6f6b 6d61726b 42617249 645d486f 6d655552 4c537472 696e675e 426f6f6b 6d61726b 4d656e75 49645c41 63636f75 6e745072 7349645c 42756c6b 52657175 65737473 5953796e 63546f6b 656e5e50 75736854 72616e73 706f7274 735d436c 69656e74 56657273 696f6e5f 10125072 696e6369 70616c55 524c5374 72696e67 5f101653 7570706f 72747353 796e6343 6f6c6c65 6374696f 6e5f100f 496e6974 69616c53 796e6344 6f6e655f 10195365 72766572 446f6573 4e6f7453 7570706f 72745054 6167735f 10314654 3d2d4052 553d3139 30313633 30352d35 3663392d 34333763 2d393566 342d3933 35323162 61643262 65384053 3d33315a 38343032 36333033 36385f10 72687474 70733a2f 2f62616e 73616c76 6b732534 3069636c 6f75642e 636f6d40 7033352d 626f6f6b 6d61726b 732e6963 6c6f7564 2e636f6d 2f383430 32363330 3336382f 626f6f6b 6d61726b 732f3241 36363246 45412d33 3546392d 34344335 2d383742 392d3844 44454245 30453439 31322f5f 104d6874 7470733a 2f2f6261 6e73616c 766b7325 34306963 6c6f7564 2e636f6d 40703335 2d626f6f 6b6d6172 6b732e69 636c6f75 642e636f 6d2f3834 30323633 30333638 2f626f6f 6b6d6172 6b732f5f 10726874 7470733a 2f2f6261 6e73616c 766b7325 34306963 6c6f7564 2e636f6d 40703335 2d626f6f 6b6d6172 6b732e69 636c6f75 642e636f 6d2f3834 30323633 30333638 2f626f6f 6b6d6172 6b732f43 38314331 3946322d 45364136 2d343643 372d3938 33362d44 43353841 30324234 3641422f 5a383430 32363330 333638d2 17181922 54637275 64567369 6d706c65 d41a1b1c 1d1e1f20 20586d61 782d7369 7a655d6d 61782d72 65736f75 72636573 56757064 61746556 696e7365 72741200 a0000010 c80909d3 1b1d1a1f 201e095f 103e4441 5653542d 56312d70 33352d46 543d2d40 52553d31 39303136 3330352d 35366339 2d343337 632d3935 66342d39 33353231 62616432 62653840 533d3333 d1262754 41505344 d428292a 2b2c2d2e 2f5b6170 7362756e 646c6569 6453656e 765f1010 73756273 63726970 74696f6e 2d75726c 5f101072 65667265 73682d69 6e746572 76616c5f 1010636f 6d2e6d65 2e626f6f 6b6d6172 6b735a50 524f4455 4354494f 4e5f1053 68747470 733a2f2f 62616e73 616c766b 73253430 69636c6f 75642e63 6f6d4070 33352d62 6f6f6b6d 61726b73 2e69636c 6f75642e 636f6d2f 38343032 36333033 36382f6d 6d2f7075 73682f72 65676973 74657256 31323030 30301001 5f104d68 74747073 3a2f2f62 616e7361 6c766b73 25343069 636c6f75 642e636f 6d407033 352d626f 6f6b6d61 726b732e 69636c6f 75642e63 6f6d2f38 34303236 33303336 382f7072 696e6369 70616c2f 09090008 0025002a 002f0037 00450053 0062006f 007c0086 009500a3 00b800d1 00e300ff 0133013e 01b30203 02780283 0288028d 0294029d 02a602b4 02bb02c2 02c702c9 02ca02cb 02d202d3 03140317 031c0325 03310335 0348035b 036e0379 03cf03d6 03d80428 04290000 00000000 02010000 00000000 00340000 00000000 00000000 00000000 042a>;
};
Title = "";
WebBookmarkFileVersion = 1;
WebBookmarkType = WebBookmarkTypeList;
WebBookmarkUUID = "FBAA875A-C10A-4744-98BD-DC5EC1D9A009"; }
Before converting any object into json, first check that given object is json convertible or not, you can use following code to check that
if ([NSJSONSerialization isValidJSONObject: plistDict])
{
....
}
Because a JSON Object must be of type NSArray or a NSDictionary while you are passing a NSString.
From the docs :
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
Your data structure can be successfully read into a NSDictionary instance. But when you serialize it to JSON it fails because it contains parts that cannot be represented as JSON.
My guess is that it's the data at $.Sync.ServerData. This seems to be binary data. JSON doesn't have an data type for binary data.
Remove this element before you serialize it. Or replace it with something else, e.g. a string with a Base-64 representation of the binary data.
The crucial information is
Invalid type in JSON write (__NSCFData)
JSON does not support NSData type (the value of ServerData), you might send the data as string Base64 encoded.
This is the key:
Invalid type in JSON write (__NSCFData)
You cannot serialise NSData to JSON. Try encoding it to string using base-64 (see this answer to do that).
Do this way may be it helps you
{ NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
self.handmadeEmbDict = [dict6 objectForKey:#"hemb_list"];
[handmadeEmbTable reloadData];
}
- (id)cleanJsonToObject:(id)data {
NSError* error;
if (data == (id)[NSNull null]){
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]]){
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else {
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--) {
id a = array[i];
if (a == (id)[NSNull null]){
[array removeObjectAtIndex:i];
} else {
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys]) {
id d = dictionary[key];
if (d == (id)[NSNull null]){
dictionary[key] = #"";
} else {
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else {
return jsonObject;
}
}
Swift 2
if let path = NSBundle.mainBundle().pathForResource("try", ofType: "json")
{
do {
let jsonData = try NSData(contentsOfFile:
path, options: NSDataReadingOptions.MappedRead)
let dict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableLeaves)
let rootDict = dict
Print(rootDict)
catch
{
}
}