EXC_BAD_ACCESS error code in Swift - ios

I'm creating a simple note taking iOS app with Swift.
When I attempt to save the location of the device to the note object I get an error of EXC_BAD_ACCESS(code=EXC_I386_GPFLT). I understand that this error is related to the deallocation of memory during run time, but I cant find the issue. I'm using very similar code to perform the same operation elsewhere in the app with success.
I have tried to enable Zombie object with no luck. I have also looked at a number of questions on here plus blog posts, but they did not help me find the issue (but did help me to understand it).
This is the code that the error is thrown in. I have also added the entire (non refactored) class to pastebin incase more context is needed.
var audioNote: AudioNote!
func createAudioNote() {
let appDelegate: AppDelegate = localAppDelegate()
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext!
let entityDescription:NSEntityDescription! = NSEntityDescription.entityForName("AudioNote", inManagedObjectContext: managedContext)
audioNote = AudioNote(entity: entityDescription, insertIntoManagedObjectContext: managedContext)
audioNote.date_created = NSDate()
audioNote.url = "\(soundFileURL)"
if (appDelegate.userLocation != nil){
println(appDelegate.userLocation!.coordinate.latitude)// <- Contains latitude as expected
println(audioNote)// <- Contains note as expected
audioNote.latitude = appDelegate.userLocation!.coordinate.latitude // <- Error throws here
audioNote.longitude = appDelegate.userLocation!.coordinate.longitude
}
}
The stack trace points me towards and issue with CoreData, but beyond checking the naming of the entity and attributes I'm not sure what to do.
The stack trace is as follows:
* thread #1: tid = 0x581ddd, 0x0000000112ef1017 libobjc.A.dylib`objc_msgSend + 23, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
frame #0: 0x0000000112ef1017 libobjc.A.dylib`objc_msgSend + 23
frame #1: 0x0000000111d751f5 CoreData`_PFManagedObject_coerceValueForKeyWithDescription + 1493
frame #2: 0x0000000111d4e2f1 CoreData`_sharedIMPL_setvfk_core + 177
* frame #3: 0x0000000110087c79 ELLIE`ELLIE.AudioNoteController.createAudioNote (self=<unavailable>)() -> () + 2345 at AudioNoteController.swift:117
frame #4: 0x000000011008601b ELLIE`ELLIE.AudioNoteController.saveAudioNote (sender=AnyObject at 0x00007fff4fc050e8, self=<unavailable>)(Swift.AnyObject) -> () + 59 at AudioNoteController.swift:47
frame #5: 0x0000000110086076 ELLIE`#objc ELLIE.AudioNoteController.saveAudioNote (ELLIE.AudioNoteController)(Swift.AnyObject) -> () + 54 at AudioNoteController.swift:0
frame #6: 0x0000000110a36d62 UIKit`-[UIApplication sendAction:to:from:forEvent:] + 75
frame #7: 0x0000000110b4850a UIKit`-[UIControl _sendActionsForEvents:withEvent:] + 467
frame #8: 0x0000000110b478d9 UIKit`-[UIControl touchesEnded:withEvent:] + 522
frame #9: 0x0000000110a83958 UIKit`-[UIWindow _sendTouchesForEvent:] + 735
frame #10: 0x0000000110a84282 UIKit`-[UIWindow sendEvent:] + 682
frame #11: 0x0000000110a4a541 UIKit`-[UIApplication sendEvent:] + 246
frame #12: 0x0000000110a57cdc UIKit`_UIApplicationHandleEventFromQueueEvent + 18265
frame #13: 0x0000000110a3259c UIKit`_UIApplicationHandleEventQueue + 2066
frame #14: 0x00000001124c3431 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
frame #15: 0x00000001124b92fd CoreFoundation`__CFRunLoopDoSources0 + 269
frame #16: 0x00000001124b8934 CoreFoundation`__CFRunLoopRun + 868
frame #17: 0x00000001124b8366 CoreFoundation`CFRunLoopRunSpecific + 470
frame #18: 0x0000000115c8ea3e GraphicsServices`GSEventRunModal + 161
frame #19: 0x0000000110a358c0 UIKit`UIApplicationMain + 1282
frame #20: 0x0000000110097237 ELLIE`main + 135 at AppDelegate.swift:16
frame #21: 0x0000000113628145 libdyld.dylib`start + 1
frame #22: 0x0000000113628145 libdyld.dylib`start + 1
Any help is much appreciated.
Tony

Check that you've declared your custom NSManagedObject sub-class in your Model schema. This will need to be in the fully qualified APP.ClassName format, e.g:

I'm not sure that it will help, but I'd recommend to rewrite this part:
if (appDelegate.userLocation != nil){
println(appDelegate.userLocation!.coordinate.latitude)// <- Contains latitude as expected
println(audioNote)// <- Contains note as expected
audioNote.latitude = appDelegate.userLocation!.coordinate.latitude // <- Error throws here
audioNote.longitude = appDelegate.userLocation!.coordinate.longitude
}
Like that:
if let location = appDelegate.userLocation{
print(audioNote)
audioNote.latitude = location.coordinate.latitude
audioNote.longitude = location.coordinate.longitude
}

Related

SCNAction playAudio seems to cause a crash

I am seeing a crash in SceneKit that I was not seeing before iOS 13.1.2.
I’ve traced the issue to the following function and cannot completely suss out what is causing the issue.
If I comment out the line which runs the action on the node, all is well.
I can run playAudio actions on other pre-existing nodes in the scene but when I simply want to have a one-shot sound play using the below function, the app crashes.
So my thought is that perhaps this has something to do with the way I am instantiating the node but I cannot think of another way to instantiate a node just to play a sound at a given position.
I’ve also tried using a recycled audio source but that makes no difference.
Might anyone have any ideas what might be going on in this code to cause a crash? It’s just not obvious to me, especially since this had worked flawlessly before the iOS updates.
I’ve included the back trace below.
Thanks so much for any help / ideas!
Have a great weekend!
Cheers!
func play(sound: String, atPosition: SCNVector3, volume: Float, pitch: Float, loops: Bool, positional: Bool) {
// Sources will be pre-loaded and recycled for the finished app
if let source = SCNAudioSource(fileNamed: "art.scnassets/"+sound)
{
source.volume = volume
source.rate = pitch
source.isPositional = positional
source.shouldStream = false
source.loops = loops
source.load()
let node = SCNNode()
node.name = "oneShot"
node.position = atPosition
scnScene.rootNode.addChildNode(node)
// node.runAction(SCNAction.sequence([SCNAction.playAudio(source, waitForCompletion: true), SCNAction.removeFromParentNode()]))
// This line causes the crash
node.runAction(SCNAction.playAudio(source, waitForCompletion: false))
}
}
thread #14, name = 'com.apple.scenekit.scnview-renderer', queue = 'com.apple.scenekit.renderingQueue.SCNView0x105a11e90', stop reason = EXC_BAD_ACCESS (code=1, address=0x830b67ea0)
frame #0: 0x00000001b08d7030 libobjc.A.dylibobjc_retain + 16
frame #1: 0x00000001bd5a90c4 AVFAudio-[AVAudioPlayerNode didAttachToEngine:] + 140
frame #2: 0x00000001bd5b66e8 AVFAudioAVAudioEngineImpl::AttachNode(AVAudioNode*, bool) + 272
frame #3: 0x00000001bd5b2324 AVFAudio-[AVAudioEngine attachNode:] + 80
frame #4: 0x00000001c4aea48c SceneKitCPP3DAudioContext::AddVoice(void const*) + 120
frame #5: 0x00000001c4aeacf0 SceneKitCPP3DAudioEngine::AddVoice(void const*) + 192
frame #6: 0x00000001c49bd618 SceneKitC3DNodeAddAudioPlayer + 40
frame #7: 0x00000001c4a07924 SceneKit-[SCNNode addAudioPlayer:] + 132
frame #8: 0x00000001c49325e0 SceneKitSCNCPlaySound::cpp_updateWithTargetForTime(SCNNode*, double) + 96
frame #9: 0x00000001c499c690 SceneKitSCNActionApply + 112
frame #10: 0x00000001c4a2d7a4 SceneKit_applyActions + 236
frame #11: 0x00000001b0a8e1b8 CoreFoundation-[NSFrozenDictionaryM __apply:context:] + 128
frame #12: 0x00000001c4a2d5c8 SceneKitC3DAnimationManagerApplyActions + 104
frame #13: 0x00000001c4a173e4 SceneKit-[SCNRenderer _update:] + 576
frame #14: 0x00000001c4a19a04 SceneKit-[SCNRenderer _drawSceneWithNewRenderer:] + 200
frame #15: 0x00000001c4a19fbc SceneKit-[SCNRenderer _drawScene:] + 48
frame #16: 0x00000001c4a1a350 SceneKit-[SCNRenderer _drawAtTime:] + 616
frame #17: 0x00000001c4ab46b8 SceneKit-[SCNView _drawAtTime:] + 428
frame #18: 0x00000001c497ae38 SceneKit__69-[NSObject(SCN_DisplayLinkExtensions) SCN_setupDisplayLinkWithQueue:]_block_invoke + 56
frame #19: 0x00000001c4a7fe48 SceneKit__36-[SCNDisplayLink _callbackWithTime:]_block_invoke + 64
frame #20: 0x0000000105726c04 libdispatch.dylib_dispatch_client_callout + 16
frame #21: 0x0000000105735888 libdispatch.dylib_dispatch_lane_barrier_sync_invoke_and_complete + 124
frame #22: 0x00000001c4a7fdd8 SceneKit-[SCNDisplayLink _callbackWithTime:] + 232
frame #23: 0x00000001058f95f8 GPUToolsCore-[DYDisplayLinkInterposer forwardDisplayLinkCallback:] + 168
frame #24: 0x00000001b73da514 QuartzCoreCA::Display::DisplayLink::dispatch_items(unsigned long long, unsigned long long, unsigned long long) + 632
frame #25: 0x00000001b1acdeb0 IOKitIODispatchCalloutFromCFMessage + 488
frame #26: 0x00000001b0ae96d4 CoreFoundation__CFMachPortPerform + 172
frame #27: 0x00000001b0b12e5c CoreFoundation__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 56
frame #28: 0x00000001b0b12588 CoreFoundation__CFRunLoopDoSource1 + 444
frame #29: 0x00000001b0b0d45c CoreFoundationCFRunLoopRun + 2168
frame #30: 0x00000001b0b0c8bc CoreFoundationCFRunLoopRunSpecific + 464
frame #31: 0x00000001b0e4c994 Foundation-[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 228
frame #32: 0x00000001c497b214 SceneKit__71-[SCNView(SCNDisplayLink) _initializeDisplayLinkWithCompletionHandler:]_block_invoke + 456
frame #33: 0x00000001c497b45c SceneKit__SCNRenderThread_start + 96
frame #34: 0x00000001b08b11ec libsystem_pthread.dylib`_pthread_start + 124
just wanted to update my question to say that this issue has resolved itself after updating to iOS 13.2. -My thanks to Apple. :)

Core data crashe with libc++abi.dylib: terminating with uncaught exception of type NSException

When I try to save a new object into core data I am getting this error and a crash when I try to save the context:
libc++abi.dylib: terminating with uncaught exception of type NSException
I have used the same method to save a newly created managed object in a number of other view controllers and all work fine except in this one. The issue started when I changed this line:
var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
from .mainQueueConcurrencyType in the AppDelegate.
This is my persistent store coordinator setup in AppDel:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
and this is the series of functions that lead up to the crash:
//get a new model for the components, same context, new FRC
purchaseOrderModel = StockModel()
purchaseOrderModel.setupManagedObjectContext()
purchaseOrderModel.tableView = tableView
if purchaseOrder == nil {
//delegate?.editModeStateChange(editing: true)
purchaseOrder = purchaseOrderModel.savePurchaseOrderWith("", supplier: nil, issueDate: Date(), deliveryDate: Date(), deliveryStatus: false)
delegate?.newItemAdded()
creatingNewPurchaseOrder = true
}
calls to
func savePurchaseOrderWith(_ poId: String?, supplier: NSManagedObject?, issueDate: Date, deliveryDate: Date, deliveryStatus: Bool? = nil) -> NSManagedObject {
let newPurchaseOrder = NSEntityDescription.insertNewObject(forEntityName: "Purchase_Order", into: context)
newPurchaseOrder.setValue(poId, forKey: "po_id")
newPurchaseOrder.setValue(issueDate, forKey: "issue_date")
newPurchaseOrder.setValue(deliveryDate, forKey: "est_delivery_date")
newPurchaseOrder.setValue(supplier, forKey: "supplier")
newPurchaseOrder.setValue(deliveryStatus, forKey: "delivered")
_ = doSaveContext()
return newPurchaseOrder
}
doSaveContext:
func doSaveContext() -> Bool {
do {
try context.save() //editing POs makes it crash here after changing the created context in app delegate
return true
} catch let error as NSError {
print("Error saving context after delete \(error.localizedDescription)")
return false
}
}
and I get a SIGBART on try context.save()
It's been a couple of months since I worked on this project but this is what ground development to a halt so help would be great. What is weird is that every other path that creates a new empty object (say a delivery, new product etc) that ends in doSaveContext() works fine.
Happy to post extra information etc.
Update 1: When adding an exception break point it breaks in this function of my model class:
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type{
case NSFetchedResultsChangeType.insert:
//note that for insert we insert a row at _newIndexPath_
if let insertIndexPath = newIndexPath {
self.tableView.insertRows(at: [insertIndexPath], with: UITableViewRowAnimation.fade)
}
case NSFetchedResultsChangeType.delete:
//note that for delete we delete the row at _indexPath_
if let deleteIndexPath = indexPath {
self.tableView.deleteRows(at: [deleteIndexPath], with: UITableViewRowAnimation.fade)
}
case NSFetchedResultsChangeType.update:
//note that for update we update the row at _indexPath_
if indexPath != nil {
// let cell = self.tableView.cellForRowAtIndexPath(updateIndexPath)
// let supplier = fetchedResultsController.objectAtIndexPath(updateIndexPath)
// cell!.textLabel?.text = supplier.name
}
case NSFetchedResultsChangeType.move:
//note that for Move we delete the row at _indexPath_
if let deleteIndexPath = indexPath {
self.tableView.insertRows(at: [deleteIndexPath], with: UITableViewRowAnimation.fade)
}
//note that for move we insert a row at _newIndexPath_
if let insertIndexPath = newIndexPath {
self.tableView.insertRows(at: [insertIndexPath], with: UITableViewRowAnimation.fade)
}
}
}
on the self.tableView.insertRows(at: [insertIndexPath], with: UITableViewRowAnimation.fade) line if that helps. Can't find a clear log anywhere.
Update 2: Typing bt in the console when it breaks produces this:
(lldb) bt
* thread #1, queue = 'NSManagedObjectContext 0x6040003cb8b0', stop reason = breakpoint 1.2
frame #0: 0x000000010c8e3b86 libc++abi.dylib`__cxa_throw
frame #1: 0x0000000106ee2068 libobjc.A.dylib`objc_exception_throw + 343
frame #2: 0x0000000107ff8362 CoreFoundation`+[NSException raise:format:arguments:] + 98
frame #3: 0x0000000106986089 Foundation`-[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
frame #4: 0x00000001096d9430 UIKit`-[UITableView _endCellAnimationsWithContext:] + 18124
frame #5: 0x00000001096f5524 UIKit`-[UITableView _updateRowsAtIndexPaths:withUpdateAction:rowAnimation:usingPresentationValues:] + 1342
frame #6: 0x00000001096f55f7 UIKit`-[UITableView insertRowsAtIndexPaths:withRowAnimation:] + 118
* frame #7: 0x00000001062013fd SC Dev`StockModel.controller(controller=0x00006000000efe00, anObject=Any # 0x00007fff59ae7458, indexPath=nil, type=insert, newIndexPath=2 indices, self=0x0000600000478940) at StockModel.swift:283
frame #8: 0x0000000106201f30 SC Dev`#objc StockModel.controller(_:didChange:at:for:newIndexPath:) at StockModel.swift:0
frame #9: 0x0000000107b6ef17 CoreData`__82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke + 5767
frame #10: 0x0000000107a13bf8 CoreData`developerSubmittedBlockToNSManagedObjectContextPerform + 168
frame #11: 0x000000010cccb43c libdispatch.dylib`_dispatch_client_callout + 8
frame #12: 0x000000010ccd2338 libdispatch.dylib`_dispatch_queue_barrier_sync_invoke_and_complete + 392
frame #13: 0x0000000107a13afe CoreData`-[NSManagedObjectContext performBlockAndWait:] + 286
frame #14: 0x0000000107b6d877 CoreData`-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:] + 119
frame #15: 0x0000000107f8f07c CoreFoundation`__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
frame #16: 0x0000000107f8ef7a CoreFoundation`_CFXRegistrationPost + 442
frame #17: 0x0000000107f8ecc2 CoreFoundation`___CFXNotificationPost_block_invoke + 50
frame #18: 0x0000000107f50a32 CoreFoundation`-[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1826
frame #19: 0x0000000107f4fbac CoreFoundation`_CFXNotificationPost + 652
frame #20: 0x00000001068c3842 Foundation`-[NSNotificationCenter postNotificationName:object:userInfo:] + 66
frame #21: 0x00000001079fcbd5 CoreData`-[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] + 773
frame #22: 0x0000000107a9e0ca CoreData`-[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] + 1658
frame #23: 0x00000001079f6f0f CoreData`-[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 2399
frame #24: 0x00000001079fa7d3 CoreData`-[NSManagedObjectContext save:] + 419
frame #25: 0x00000001062032fc SC Dev`StockModel.doSaveContext(self=0x0000600000673000) at StockModel.swift:381
frame #26: 0x000000010620affd SC Dev`StockModel.savePurchaseOrderWith(poId="", supplier=nil, issueDate=2018-02-06 21:17:37 UTC, deliveryDate=2018-02-06 21:17:37 UTC, deliveryStatus=false, self=0x0000600000673000) at StockModel.swift:592
frame #27: 0x000000010626ce76 SC Dev`PurchaseOrderDetailViewController.viewDidLoad(self=0x00007f941e038800) at PurchaseOrderDetailViewController.swift:68
frame #28: 0x0000000106270f84 SC Dev`#objc PurchaseOrderDetailViewController.viewDidLoad() at PurchaseOrderDetailViewController.swift:0
frame #29: 0x000000010975ad51 UIKit`-[UIViewController loadViewIfRequired] + 1235
frame #30: 0x00000001097a24dc UIKit`-[UINavigationController _updateScrollViewFromViewController:toViewController:] + 68
frame #31: 0x00000001097a2818 UIKit`-[UINavigationController _startTransition:fromViewController:toViewController:] + 153
frame #32: 0x00000001097a392f UIKit`-[UINavigationController _startDeferredTransitionIfNeeded:] + 841
frame #33: 0x00000001097a4b90 UIKit`-[UINavigationController __viewWillLayoutSubviews] + 115
frame #34: 0x00000001099fb2ae UIKit`-[UILayoutContainerView layoutSubviews] + 231
frame #35: 0x000000010968b551 UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1331
frame #36: 0x00000001093fb4ba QuartzCore`-[CALayer layoutSublayers] + 153
frame #37: 0x00000001093ff5a9 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 401
frame #38: 0x00000001093881cd QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 365
frame #39: 0x00000001093b3ae4 QuartzCore`CA::Transaction::commit() + 500
frame #40: 0x00000001095e7687 UIKit`_afterCACommitHandler + 272
frame #41: 0x0000000107f95db7 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
frame #42: 0x0000000107f95d0e CoreFoundation`__CFRunLoopDoObservers + 430
frame #43: 0x0000000107f7a324 CoreFoundation`__CFRunLoopRun + 1572
frame #44: 0x0000000107f79a89 CoreFoundation`CFRunLoopRunSpecific + 409
frame #45: 0x000000010f6de9c6 GraphicsServices`GSEventRunModal + 62
frame #46: 0x00000001095bcd30 UIKit`UIApplicationMain + 159
frame #47: 0x0000000106142607 SC Dev`main at AppDelegate.swift:18
frame #48: 0x000000010cd47d81 libdyld.dylib`start + 1
Update 3: wrapping the _ = doSaveContext() in DispatchQueue.main.async { gets me a few steps further along but still breaks on the same table insert line as before with the below log.
bt
* thread #1, queue = 'NSManagedObjectContext 0x6000001da400', stop reason = breakpoint 1.1
frame #0: 0x000000010945bf11 libobjc.A.dylib`objc_exception_throw
frame #1: 0x000000010a572362 CoreFoundation`+[NSException raise:format:arguments:] + 98
frame #2: 0x0000000108f00089 Foundation`-[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
frame #3: 0x000000010b9e0430 UIKit`-[UITableView _endCellAnimationsWithContext:] + 18124
frame #4: 0x000000010b9fc524 UIKit`-[UITableView _updateRowsAtIndexPaths:withUpdateAction:rowAnimation:usingPresentationValues:] + 1342
frame #5: 0x000000010b9fc5f7 UIKit`-[UITableView insertRowsAtIndexPaths:withRowAnimation:] + 118
* frame #6: 0x000000010877a0cd SC Dev`StockModel.controller(controller=0x00006000000fea00, anObject=Any # 0x00007fff575731c8, indexPath=nil, type=insert, newIndexPath=2 indices, self=0x000060400046aa00) at StockModel.swift:283
frame #7: 0x000000010877ac00 SC Dev`#objc StockModel.controller(_:didChange:at:for:newIndexPath:) at StockModel.swift:0
frame #8: 0x000000010a0e8f17 CoreData`__82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke + 5767
frame #9: 0x0000000109f8dbf8 CoreData`developerSubmittedBlockToNSManagedObjectContextPerform + 168
frame #10: 0x000000010f23843c libdispatch.dylib`_dispatch_client_callout + 8
frame #11: 0x000000010f23f338 libdispatch.dylib`_dispatch_queue_barrier_sync_invoke_and_complete + 392
frame #12: 0x0000000109f8dafe CoreData`-[NSManagedObjectContext performBlockAndWait:] + 286
frame #13: 0x000000010a0e7877 CoreData`-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:] + 119
frame #14: 0x000000010a50907c CoreFoundation`__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
frame #15: 0x000000010a508f7a CoreFoundation`_CFXRegistrationPost + 442
frame #16: 0x000000010a508cc2 CoreFoundation`___CFXNotificationPost_block_invoke + 50
frame #17: 0x000000010a4caa32 CoreFoundation`-[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1826
frame #18: 0x000000010a4c9bac CoreFoundation`_CFXNotificationPost + 652
frame #19: 0x0000000108e3d842 Foundation`-[NSNotificationCenter postNotificationName:object:userInfo:] + 66
frame #20: 0x0000000109f76bd5 CoreData`-[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] + 773
frame #21: 0x000000010a0180ca CoreData`-[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] + 1658
frame #22: 0x0000000109f70f0f CoreData`-[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 2399
frame #23: 0x0000000109f747d3 CoreData`-[NSManagedObjectContext save:] + 419
frame #24: 0x000000010877bfcc SC Dev`StockModel.doSaveContext(self=0x000060000046fec0) at StockModel.swift:381
frame #25: 0x0000000108783ebe SC Dev`closure #1 in StockModel.savePurchaseOrderWith(self=0x000060000046fec0) at StockModel.swift:593
frame #26: 0x0000000108783f52 SC Dev`partial apply for closure #1 in StockModel.savePurchaseOrderWith(_:supplier:issueDate:deliveryDate:deliveryStatus:) at StockModel.swift:0
frame #27: 0x00000001086c0b89 SC Dev`thunk for #callee_owned () -> () at AddProductViewController.swift:0
frame #28: 0x000000010f2373f7 libdispatch.dylib`_dispatch_call_block_and_release + 12
frame #29: 0x000000010f23843c libdispatch.dylib`_dispatch_client_callout + 8
frame #30: 0x000000010f2436f0 libdispatch.dylib`_dispatch_main_queue_callback_4CF + 628
frame #31: 0x000000010a52fef9 CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
frame #32: 0x000000010a4f4662 CoreFoundation`__CFRunLoopRun + 2402
frame #33: 0x000000010a4f3a89 CoreFoundation`CFRunLoopRunSpecific + 409
frame #34: 0x0000000111c579c6 GraphicsServices`GSEventRunModal + 62
frame #35: 0x000000010b8c3d30 UIKit`UIApplicationMain + 159
frame #36: 0x00000001086bb2d7 SC Dev`main at AppDelegate.swift:18
frame #37: 0x000000010f2b4d81 libdyld.dylib`start + 1
(lldb)
It's impossible to be certain but your stack traces strongly suggest that the problem is related to updating your table view from NSFetchedResultsControllerDelegate callbacks. From one of your comments, the likeliest cause is that you're not calling beginUpdates() on the table view anywhere.
There are two basic approaches to updating a table view from NSFetchedResultsControllerDelegate. First, simple but not optimal: Don't implement controllerWillChangeContent(_:) or controller(_:didChange:at:for:newIndexPath:). Do implement controllerDidChangeContent(_:), but use that method to reloadData() on your table view. Don't bother with begin/end updates or inserting/deleting/etc rows.
The second, better but slightly more complex, is to do all of these:
Implement controllerWillChangeContent(_:) and use it to call beginUpdates().
Implement controller(_:didChange:at:for:newIndexPath:) to insert/update/etc rows in the table.
Implement controllerDidChangeContent(_:) and use it to call endUpdates().
The "begin" and "end" calls are both crucial. I can't be 100% sure that this is what's causing your specific crash, but I'd expect leaving out beginUpdates() to cause some kind of crash.

EXC_BAD_ACCESS (code=1, address=0x0)

I have a piece of code which runs correctly in real device but is giving EXC_BAD_ACCESS (code=1, address=0x0) error in simulator (iphone 6) :
The bt output is:
(lldb) bt
* thread #1: tid = 0xe40f6, 0x00000001052ab5e9 CoreFoundation`CFArrayGetCount + 25, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x00000001052ab5e9 CoreFoundation`CFArrayGetCount + 25
* frame #1: 0x0000000104c6a5af MyApp`static MyApp.SSID.fetchSSIDInfo (self=MyApp.SSID)() -> Swift.String + 95 at WifiGetter.swift:17
frame #2: 0x0000000104c4994a MyApp`MyApp.TableViewController.sendWifi (self=0x00007ff05a64da80)() -> () + 26 at TableViewController.swift:355
frame #3: 0x0000000104c49316 MyApp`MyApp.TableViewController.fetchData (self=0x00007ff05a64da80)() -> () + 38 at TableViewController.swift:308
frame #4: 0x0000000104c4567f MyApp`MyApp.TableViewController.viewDidLoad (self=0x00007ff05a64da80)() -> () + 3215 at TableViewController.swift:66
frame #5: 0x0000000104c45ea2 MyApp`#objc MyApp.TableViewController.viewDidLoad (MyApp.TableViewController)() -> () + 34 at TableViewController.swift:0
frame #6: 0x00000001063c9931 UIKit`-[UIViewController loadViewIfRequired] + 1344
frame #7: 0x000000010640cc26 UIKit`-[UINavigationController _layoutViewController:] + 54
frame #8: 0x000000010640d4dd UIKit`-[UINavigationController _updateScrollViewFromViewController:toViewController:] + 433
frame #9: 0x000000010640d633 UIKit`-[UINavigationController _startTransition:fromViewController:toViewController:] + 116
frame #10: 0x000000010640e879 UIKit`-[UINavigationController _startDeferredTransitionIfNeeded:] + 890
frame #11: 0x000000010640f67d UIKit`-[UINavigationController __viewWillLayoutSubviews] + 57
frame #12: 0x00000001065a763d UIKit`-[UILayoutContainerView layoutSubviews] + 248
frame #13: 0x00000001062ef11c UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 710
frame #14: 0x000000010c35836a QuartzCore`-[CALayer layoutSublayers] + 146
frame #15: 0x000000010c34cbd0 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 366
frame #16: 0x000000010c34ca4e QuartzCore`CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 24
frame #17: 0x000000010c3411d5 QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 277
frame #18: 0x000000010c36e9f0 QuartzCore`CA::Transaction::commit() + 508
frame #19: 0x000000010c36f154 QuartzCore`CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 92
frame #20: 0x00000001053079d7 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
frame #21: 0x0000000105307947 CoreFoundation`__CFRunLoopDoObservers + 391
frame #22: 0x00000001052fcebc CoreFoundation`CFRunLoopRunSpecific + 524
frame #23: 0x000000010623998d UIKit`-[UIApplication _run] + 402
frame #24: 0x000000010623e676 UIKit`UIApplicationMain + 171
frame #25: 0x0000000104c20efd MyApp`main + 109 at AppDelegate.swift:20
frame #26: 0x0000000108ea592d libdyld.dylib`start + 1
interfaces is nil. You must handle this case. I recommend avoiding !. Making the type non-optional here will allow the if let binding to work correctly.
You should change your if let clause to if let interfaces = CNCopySupportedInterfaces() as? CFArray.
Because you use if let interfaces: CFArray! with ! mean force unwrap, therefore, when CNCopySupportedInterfaces() return nil or value which is not convertible to CFArray, force unwrap will cause crash

EXC_BAD_INSTRUCTION upon pressing a button

I'm newbie in Swift and I'm currenlty trying to learn it but I faced a mystery issue. As you can see in the image below, there are some controls that are linked properly to this View Controller and upon pressing a button in the UI we execute this code below but I always got an EXC_BAD_INSTRUCTION. I don't understand why!!
Here is some info from the stack trace.
(lldb) thread info
thread #1: tid = 0x9319, 0x0006c5d5 App`App.AViewController.sendCommentViaEmail (self=<unavailable>)() -> () + 9349 at AViewController.swift:49, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
(lldb) frame select 1
frame #1: 0x037067cd libobjc.A.dylib`-[NSObject performSelector:withObject:withObject:] + 84
libobjc.A.dylib`-[NSObject performSelector:withObject:withObject:] + 84:
-> 0x37067cd: addl $0x1c, %esp
0x37067d0: popl %esi
0x37067d1: popl %edi
0x37067d2: popl %ebx
EDITED:
Stacktrace below
* thread #1: tid = 0x1e19, 0x0005a5d5 A`A.AViewController.sendCommentViaEmail (self=<unavailable>)() -> () + 9349 at AViewController.swift:49, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
* frame #0: 0x0005a5d5 A`A.AViewController.sendCommentViaEmail (self=<unavailable>)() -> () + 9349 at AViewController.swift:49
frame #1: 0x036f47cd libobjc.A.dylib`-[NSObject performSelector:withObject:withObject:] + 84
frame #2: 0x01ea323d UIKit`-[UIApplication sendAction:to:from:forEvent:] + 99
frame #3: 0x02213840 UIKit`-[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 139
frame #4: 0x036f47cd libobjc.A.dylib`-[NSObject performSelector:withObject:withObject:] + 84
frame #5: 0x01ea323d UIKit`-[UIApplication sendAction:to:from:forEvent:] + 99
frame #6: 0x01ea31cf UIKit`-[UIApplication sendAction:toTarget:fromSender:forEvent:] + 64
frame #7: 0x01fd6e86 UIKit`-[UIControl sendAction:to:forEvent:] + 69
frame #8: 0x01fd72a3 UIKit`-[UIControl _sendActionsForEvents:withEvent:] + 598
frame #9: 0x01fd650d UIKit`-[UIControl touchesEnded:withEvent:] + 660
frame #10: 0x01ef360a UIKit`-[UIWindow _sendTouchesForEvent:] + 874
frame #11: 0x01ef40e5 UIKit`-[UIWindow sendEvent:] + 791
frame #12: 0x01eb9549 UIKit`-[UIApplication sendEvent:] + 242
frame #13: 0x01ec937e UIKit`_UIApplicationHandleEventFromQueueEvent + 20690
frame #14: 0x01e9db19 UIKit`_UIApplicationHandleEventQueue + 2206
frame #15: 0x039791df CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
frame #16: 0x0396eced CoreFoundation`__CFRunLoopDoSources0 + 253
frame #17: 0x0396e248 CoreFoundation`__CFRunLoopRun + 952
frame #18: 0x0396dbcb CoreFoundation`CFRunLoopRunSpecific + 443
frame #19: 0x0396d9fb CoreFoundation`CFRunLoopRunInMode + 123
frame #20: 0x085dc24f GraphicsServices`GSEventRunModal + 192
frame #21: 0x085dc08c GraphicsServices`GSEventRun + 104
frame #22: 0x01ea18b6 UIKit`UIApplicationMain + 1526
frame #23: 0x000919cc A`main(argc=1, argv=0xbffaa62c) + 76 at main.m:12
frame #24: 0x04490ac9 libdyld.dylib`start + 1
Here are the properties I'm using:
I got the same result whether they are linked to the UI or not.
Where does emailToMyselfSwitch come from? If it's an IBOutlet it seems that you forgot to connect it from IB to your code. If that's not the case please show more context.
This error EXC_BAD_INSTRUCTION generally means that you are calling a property or method (selector?) on a null object or an object that can't respond to the selector ie self.null.on or a property that cannot be accessed because it was released.
I've had trouble in the past with these weak vars falling away. Try deleting the weak in your property.
your code is correct. The problem is not in the connection with outlet. I´ve tested and prints: "Value: nil"
The problem is in other part of code.
The message "self=" is not normal.
You can show us more information.

Extremely Odd Crash When saving a transformable NSAttributedString into Core Data

I have a project using Core Data. It has a Note object which has one transformable attribute called content. I am storing an NSAttributedString into this property. The property saves fine for the first save, but when I try to create a second note object, the app crashes.
Here is the code I use to save:
- (IBAction)save:(id)sender {
Note* newNote = [NSEntityDescription insertNewObjectForEntityForName:#"Note" inManagedObjectContext:[self managedObjectContext]];
NSAttributedString* string = [[self textView]attributedText];
[newNote setContent:string];
NSArray* tokens = [[self tokenField]tokens];
NSError* error = nil;
if (![[self managedObjectContext]save:&error]) {
NSLog(#"Error saving %#",[error localizedDescription]);
}
[[self navigationController]popViewControllerAnimated:YES];
}
Again this code saves with no problem when there are no objects in the persistent store.
When I attempt to save a new object (in a non empty store:) this exception is thrown first (I have a break point set for all exceptions)
-[NSConcreteMutableAttributedString compare:]: unrecognized selector sent to instance 0x1759e8b0
Then when I continue, I get this:
2013-07-18 10:17:39.011 Meta[2417:60b] CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[NSConcreteMutableAttributedString compare:]: unrecognized selector sent to instance 0x1759e8b0 with userInfo (null)
2013-07-18 10:17:39.014 Meta[2417:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableAttributedString compare:]: unrecognized selector sent to instance 0x1759e8b0'
I am also using an NSManagedObject subclass which is implemented as follows:
#interface Note : NSManagedObject
#property (nonatomic, strong) id content;
#end
Again content is where I am attempting to store the attributed string
I have tried using the default NSValueTransformer and my own subclass. Both cause the same problem.
Edit: Here is the implementation of my value transformer:
#import "AttributedStringValueTransformer.h"
#implementation AttributedStringValueTransformer
+(Class)transformedValueClass {
return [NSAttributedString class];
}
+(void)initialize {
[NSValueTransformer setValueTransformer:[[self alloc]init] forName:#"NSAttributedStringValueTransformer"];
}
+(BOOL)allowsReverseTransformation {
return YES;
}
-(NSData*)transformedValue:(NSAttributedString*)value {
NSData* stringAsData = [NSKeyedArchiver archivedDataWithRootObject:value];
return stringAsData;
}
-(NSAttributedString*)reverseTransformedValue:(NSData*)value {
NSAttributedString* string = [NSKeyedUnarchiver unarchiveObjectWithData:value];
return string;
}
Edit: Here is the backtrace:
(lldb) bt
* thread #1: tid = 0x5d2ef, 0x39a3d688 libobjc.A.dylib`objc_exception_throw, queue = 'com.apple.main-thread, stop reason = breakpoint 1.1
frame #0: 0x39a3d688 libobjc.A.dylib`objc_exception_throw
frame #1: 0x2f958fa2 CoreFoundation`-[NSObject(NSObject) doesNotRecognizeSelector:] + 202
frame #2: 0x2f95787a CoreFoundation`___forwarding___ + 706
frame #3: 0x2f8a5528 CoreFoundation`__forwarding_prep_0___ + 24
frame #4: 0x302a5d48 Foundation`_NSCompareObject + 32
frame #5: 0x3034fe7e Foundation`-[NSSortDescriptor compareObject:toObject:] + 270
frame #6: 0x2f79e5f4 CoreData`+[NSFetchedResultsController(PrivateMethods) _insertIndexForObject:inArray:lowIdx:highIdx:sortDescriptors:] + 216
frame #7: 0x2f79ada6 CoreData`-[NSFetchedResultsController(PrivateMethods) _postprocessInsertedObjects:] + 514
frame #8: 0x2f79c842 CoreData`-[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] + 1898
frame #9: 0x2f89c836 CoreFoundation`_CFXNotificationPost + 1718
frame #10: 0x302a13b0 Foundation`-[NSNotificationCenter postNotificationName:object:userInfo:] + 76
frame #11: 0x2f72280a CoreData`-[NSManagedObjectContext(_NSInternalNotificationHandling) _postObjectsDidChangeNotificationWithUserInfo:] + 78
frame #12: 0x2f721b0a CoreData`-[NSManagedObjectContext(_NSInternalChangeProcessing) _createAndPostChangeNotification:withDeletions:withUpdates:withRefreshes:] + 298
frame #13: 0x2f6a0af6 CoreData`-[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 2346
frame #14: 0x2f7159ba CoreData`-[NSManagedObjectContext save:] + 190
frame #15: 0x00106f82 Meta`-[NewNoteViewController save:](self=0x15dd2030, _cmd=0x325ba35a, sender=0x15dc5a70) + 918 at NewNoteViewController.m:176
frame #16: 0x320482a2 UIKit`-[UIApplication sendAction:to:from:forEvent:] + 90
frame #17: 0x32048330 UIKit`-[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 120
frame #18: 0x320482a2 UIKit`-[UIApplication sendAction:to:from:forEvent:] + 90
frame #19: 0x32048242 UIKit`-[UIApplication sendAction:toTarget:fromSender:forEvent:] + 30
frame #20: 0x32048220 UIKit`-[UIControl sendAction:to:forEvent:] + 44
frame #21: 0x3217cfce UIKit`-[UIControl _sendActionsForEvents:withEvent:] + 374
frame #22: 0x32048036 UIKit`-[UIControl touchesEnded:withEvent:] + 590
frame #23: 0x31f830e0 UIKit`-[UIWindow _sendTouchesForEvent:] + 528
frame #24: 0x31f718f0 UIKit`-[UIApplication sendEvent:] + 196
frame #25: 0x32114406 UIKit`_UIApplicationHandleHIDEvent + 6262
frame #26: 0x306765ce IOKit`__IOHIDEventSystemClientQueueCallback + 222
frame #27: 0x2f911f04 CoreFoundation`__CFMachPortPerform + 136
frame #28: 0x2f91d206 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 34
frame #29: 0x2f91d1a2 CoreFoundation`__CFRunLoopDoSource1 + 346
frame #30: 0x2f91b966 CoreFoundation`__CFRunLoopRun + 1398
frame #31: 0x2f892446 CoreFoundation`CFRunLoopRunSpecific + 522
frame #32: 0x2f89222a CoreFoundation`CFRunLoopRunInMode + 106
frame #33: 0x343f06da GraphicsServices`GSEventRunModal + 138
frame #34: 0x31fbae00 UIKit`UIApplicationMain + 1136
frame #35: 0x00105374 Meta`main(argc=1, argv=0x27d07d1c) + 116 at main.m:16
Found it:
* thread #1: tid = 0x5d2ef, 0x39a3d688 libobjc.A.dylib`objc_exception_throw, queue = 'com.apple.main-thread, stop reason = breakpoint 1.1
frame #0: 0x39a3d688 libobjc.A.dylib`objc_exception_throw
frame #1: 0x2f958fa2 CoreFoundation`-[NSObject(NSObject) doesNotRecognizeSelector:] + 202
frame #2: 0x2f95787a CoreFoundation`___forwarding___ + 706
frame #3: 0x2f8a5528 CoreFoundation`__forwarding_prep_0___ + 24
frame #4: 0x302a5d48 Foundation`_NSCompareObject + 32
frame #5: 0x3034fe7e Foundation`-[NSSortDescriptor compareObject:toObject:] + 270**
frame #6: 0x2f79e5f4 CoreData`+[NSFetchedResultsController(PrivateMethods) _insertIndexForObject:inArray:lowIdx:highIdx:sortDescriptors:] + 216
frame #7: 0x2f79ada6 CoreData`-[NSFetchedResultsController(PrivateMethods) _postprocessInsertedObjects:] + 514
frame #8: 0x2f79c842 CoreData`-[NSFetchedResultsController(PrivateMethods) _managedObjectContextDidChange:] + 1898
As the save happened, the fetched results controller started to update the tableview (which was on the presenting view controller).
I have a tableview controller subclass that I use for easy setup that takes a sort descriptor key (as a string) and internally turns it into an array and sets up the fetch request.
[self setSortDescriptorKey:#"content"];
Content is my transformable attribute in the data model (Transforms a NSAttributedString).
Originally it was just a normal string, but I needed to store attribute data as well. After changing it, the FRC was sending compare to it. I fixed it by changing the sort descriptor key:
[self setSortDescriptorKey:#"content.string"];

Resources