6
votes

I'm trying to catch memory leak and retain cycles with Leak Profiler in Instruments tool. However, whenever I click the record button in Instruments, app looks like to start then crash. If I open the app from Xcode and transfer it to Instruments, App crash after I click any of the UIButton. If I open app from Simulator, I can get the second screen but then It also crashes. In addition, App doesn't show any leak in memory graph and also doesn't crash on normal usage.

Here is the crash log;

Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000018 VM Region Info: 0x18 is not in any region. Bytes before following region: 4377985000 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START --->
__TEXT 0000000104f2c000-0000000104fbc000 [ 576K] r-x/r-x SM=COW ...ti App Test]

Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [0] Triggered by Thread: 0

Filtered syslog: None found

Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libswiftCore.dylib 0x000000010597b2b4 0x1058cc000 + 717492 1 libswiftCore.dylib
0x000000010598823c 0x1058cc000 + 770620 2 UIFoundation
0x000000018f01fbdc attributeDictionaryHash + 460 3 Foundation
0x0000000185417edc hashProbe + 72 4 Foundation
0x0000000185417e7c -[NSConcreteHashTable getItem:] + 40 5
UIFoundation 0x000000018f01fd54 +[NSAttributeDictionary newWithDictionary:] + 136 6 Foundation 0x000000018542666c -[NSConcreteAttributedString initWithString:attributes:] + 124 7 My App Test
0x0000000104fbb894 0x104f2c000 + 587924 8 My App Test
0x0000000104fba588 0x104f2c000 + 583048 9 My App Test
0x0000000104fba494 0x104f2c000 + 582804 10 My App Test
0x0000000104fb9964 0x104f2c000 + 579940 11 My App Test
0x0000000104fb9830 0x104f2c000 + 579632 12 My App Test
0x0000000104fcb608 0x104f2c000 + 652808 13 My App Test
0x0000000104fccea4 0x104f2c000 + 659108 14 My App Test
0x0000000104fcc50c 0x104f2c000 + 656652 15 My App Test
0x0000000104fcc5a0 0x104f2c000 + 656800 16 UIKit
0x000000018df36bfc -[UIViewController loadViewIfRequired] + 1040 17 UIKit 0x000000018df367d4 -[UIViewController view] + 28 18 My App Test 0x0000000104f85b6c 0x104f2c000 + 367468 19 My App Test 0x0000000104f85470 0x104f2c000 + 365680 20 My App Test 0x0000000104f85688 0x104f2c000 + 366216 21 UIKit 0x000000018df6b20c -[UIApplication sendAction:to:from:forEvent:] + 96 22 UIKit 0x000000018df6b18c -[UIControl sendAction:to:forEvent:] + 80 23 UIKit 0x000000018df55f4c -[UIControl _sendActionsForEvents:withEvent:] + 440 24 UIKit 0x000000018df6aa80 -[UIControl touchesEnded:withEvent:] + 576 25 UIKit 0x000000018df6a5a0 -[UIWindow _sendTouchesForEvent:] + 2544 26 UIKit 0x000000018df65a70 -[UIWindow sendEvent:] + 3208 27 UIKit
0x000000018df37078 -[UIApplication sendEvent:] + 340 28 UIKit
0x000000018e876f98 dispatchPreprocessedEventFromEventQueue + 2364 29 UIKit 0x000000018e879408 __handleEventQueueInternal + 4760 30 UIKit 0x000000018e872574 __handleHIDEventFetcherDrain + 152 31 CoreFoundation 0x0000000184ad0358 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 24 32 CoreFoundation 0x0000000184ad02d8 __CFRunLoopDoSource0 + 88 33 CoreFoundation 0x0000000184acfb60 __CFRunLoopDoSources0 + 204 34 CoreFoundation 0x0000000184acd738 __CFRunLoopRun + 1048 35 CoreFoundation
0x00000001849ee2d8 CFRunLoopRunSpecific + 436 36 GraphicsServices
0x000000018687ff84 GSEventRunModal + 100 37 UIKit
0x000000018df9a880 UIApplicationMain + 208 38 My App Test
0x0000000104f97854 0x104f2c000 + 440404 39 libdyld.dylib
0x000000018451256c start + 4

Thread 1: 0 libsystem_kernel.dylib 0x0000000184641dbc __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x0000000184753144 _pthread_wqthread + 1288 2
libsystem_pthread.dylib 0x0000000184752c30 start_wqthread + 4

Thread 2: 0 libsystem_pthread.dylib 0x0000000184752c2c start_wqthread + 0

Thread 3 name: com.apple.uikit.eventfetch-thread Thread 3: 0
libsystem_kernel.dylib 0x0000000184620bc4 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x0000000184620a3c mach_msg + 72 2
CoreFoundation 0x0000000184acfce4 CFRunLoopServiceMachPort + 196 3 CoreFoundation 0x0000000184acd8b0 __CFRunLoopRun + 1424 4 CoreFoundation
0x00000001849ee2d8 CFRunLoopRunSpecific + 436 5 Foundation
0x00000001854166e4 -[NSRunLoop+ 50916 (NSRunLoop) runMode:beforeDate:] + 304 6 Foundation
0x0000000185435afc -[NSRunLoop+ 178940 (NSRunLoop) runUntilDate:] + 96 7 UIKit 0x000000018eae602c -[UIEventFetcher threadMain] + 136 8 Foundation 0x0000000185517860 __NSThread__start
+ 996 9
libsystem_pthread.dylib 0x000000018475432c _pthread_body + 308 10 libsystem_pthread.dylib 0x00000001847541f8 _pthread_body + 0 11 libsystem_pthread.dylib 0x0000000184752c38 thread_start + 4

Thread 4: 0 libsystem_pthread.dylib 0x0000000184752c2c start_wqthread + 0

Thread 5 name: com.apple.NSURLConnectionLoader Thread 5: 0
libsystem_kernel.dylib 0x0000000184620bc4 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x0000000184620a3c mach_msg + 72 2
CoreFoundation 0x0000000184acfce4 CFRunLoopServiceMachPort + 196 3 CoreFoundation 0x0000000184acd8b0 __CFRunLoopRun + 1424 4 CoreFoundation
0x00000001849ee2d8 CFRunLoopRunSpecific + 436 5 CFNetwork
0x0000000185157b40 +[NSURLConnection+ 715584 (Loader) _resourceLoadLoop:] + 404 6 Foundation 0x0000000185517860 __NSThread__start
+ 996 7
libsystem_pthread.dylib 0x000000018475432c _pthread_body + 308 8 libsystem_pthread.dylib 0x00000001847541f8 _pthread_body + 0 9 libsystem_pthread.dylib 0x0000000184752c38 thread_start + 4

Thread 0 crashed with ARM Thread State (64-bit): x0: 0x00000001c4227ac0 x1: 0x000000018eca2db2 x2: 0x000000016aecf908 x3: 0x0000000000000000 x4: 0x0000000000000000 x5: 0x0000000000000020 x6: 0x0000000185426654 x7: 0x0000000000000130 x8: 0x0000000000000000 x9: 0x0000000000000000 x10: 0x0119490101194980 x11: 0x0000000001194901 x12: 0x0000000001194800 x13: 0x0000000000000001 x14: 0x0000000000000000 x15: 0x01194901011949c0 x16: 0x0000000000000000 x17: 0x0000000105988228 x18: 0x0000000000000000 x19: 0x00000001c4227ac0 x20: 0x00000001c4227ac0 x21: 0x00000001b5421000 x22: 0x00000001c0124f60 x23: 0x0000000000000000 x24: 0x00000001c0200730 x25: 0x0000000000000000 x26: 0x000000018eca3f46 x27: 0x00000001b3bca000
x28: 0x00000001c04578e0 fp: 0x000000016aecf4f0 lr: 0x000000010598823c sp: 0x000000016aecf4e0 pc: 0x000000010597b2b4 cpsr: 0x20000000

I was searching this for a month and I'm not sure If It is a Instruments bug. I checked below posts;

Xcode Instruments: Leaks - App crashes on launch

Instruments crashing while using Leaks instrument

xcode instruments causing app crash

EDIT: Another crash log. In this one I open the app and transfer memory to Instruments tool and touch a UIView top open a new controller.

Date/Time: 2018-07-06 15:13:34.5980 +0300 Launch Time: 2018-07-06 15:13:19.6298 +0300 OS Version: iPhone OS 11.0 (15A372) Baseband Version: 2.00.01 Report Version: 104

Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000018 VM Region Info: 0x18 is not in any region. Bytes before following region: 4330094568 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START --->
__TEXT 0000000102180000-00000001022a0000 [ 1152K] r-x/r-x SM=COW ...ti Filo Test]

Termination Signal: Segmentation fault: 11 Termination Reason: Namespace SIGNAL, Code 0xb Terminating Process: exc handler [0] Triggered by Thread: 0

Filtered syslog: None found

Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libswiftCore.dylib 0x0000000102bdf278 0x102b30000 + 717432 1 libswiftCore.dylib
0x0000000102bec1b0 0x102b30000 + 770480 2 CoreFoundation
0x0000000184a3ec80 -[NSDictionary allKeys] + 108 3 UIKit
0x000000018e15738c -[NSDictionary+ 2294668 (UIStringDrawingKeyCompatibility) _ui_attributesForDictionaryContainingUIStringDrawingKeys] + 36 4 UIKit 0x000000018e09fde0 -[UINavigationBar setTitleTextAttributes:] + 144 5 My App Test
0x00000001021e82e8 0x102180000 + 426728 6 My App Test
0x00000001021e67c8 0x102180000 + 419784 7 My App Test
0x00000001021e6a14 0x102180000 + 420372 8 UIKit
0x000000018e5c3f78 -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:] + 64 9 UIKit 0x000000018e5c84dc _UIGestureRecognizerSendTargetActions + 124 10 UIKit 0x000000018e0b2dc8 _UIGestureRecognizerSendActions + 320 11 UIKit 0x000000018df67748 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 732 12 UIKit 0x000000018e5b23fc _UIGestureEnvironmentUpdate + 1056 13 UIKit
0x000000018e5b1f88 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 404 14 UIKit 0x000000018e5b10e4 -[UIGestureEnvironment _updateGesturesForEvent:window:] + 276 15 UIKit 0x000000018df65a54 -[UIWindow sendEvent:] + 3180 16 UIKit
0x000000018df37078 -[UIApplication sendEvent:] + 340 17 UIKit
0x000000018e876f98 dispatchPreprocessedEventFromEventQueue + 2364 18 UIKit 0x000000018e879408 __handleEventQueueInternal + 4760 19 UIKit 0x000000018e872574 __handleHIDEventFetcherDrain + 152 20 CoreFoundation 0x0000000184ad0358 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 24 21 CoreFoundation 0x0000000184ad02d8 __CFRunLoopDoSource0 + 88 22 CoreFoundation 0x0000000184acfb60 __CFRunLoopDoSources0 + 204 23 CoreFoundation 0x0000000184acd738 __CFRunLoopRun + 1048 24 CoreFoundation
0x00000001849ee2d8 CFRunLoopRunSpecific + 436 25 GraphicsServices
0x000000018687ff84 GSEventRunModal + 100 26 UIKit
0x000000018df9a880 UIApplicationMain + 208 27 My App Test
0x00000001021facdc 0x102180000 + 503004 28 libdyld.dylib
0x000000018451256c start + 4

Thread 1: 0 libsystem_pthread.dylib 0x0000000184752c2c start_wqthread + 0

Thread 2: 0 libsystem_pthread.dylib 0x0000000184752c2c start_wqthread + 0

Thread 3: 0 libsystem_pthread.dylib 0x0000000184752c2c start_wqthread + 0

Thread 4 name: com.apple.uikit.eventfetch-thread Thread 4: 0
libsystem_kernel.dylib 0x0000000184620bc4 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x0000000184620a3c mach_msg + 72 2
CoreFoundation 0x0000000184acfce4 CFRunLoopServiceMachPort + 196 3 CoreFoundation 0x0000000184acd8b0 __CFRunLoopRun + 1424 4 CoreFoundation
0x00000001849ee2d8 CFRunLoopRunSpecific + 436 5 Foundation
0x00000001854166e4 -[NSRunLoop+ 50916 (NSRunLoop) runMode:beforeDate:] + 304 6 Foundation
0x0000000185435afc -[NSRunLoop+ 178940 (NSRunLoop) runUntilDate:] + 96 7 UIKit 0x000000018eae602c -[UIEventFetcher threadMain] + 136 8 Foundation 0x0000000185517860 __NSThread__start
+ 996 9
libsystem_pthread.dylib 0x000000018475432c _pthread_body + 308 10 libsystem_pthread.dylib 0x00000001847541f8 _pthread_body + 0 11 libsystem_pthread.dylib 0x0000000184752c38 thread_start + 4

Thread 5 name: GAIThread Thread 5: 0 libsystem_kernel.dylib
0x0000000184620bc4 mach_msg_trap + 8 1 libsystem_kernel.dylib
0x0000000184620a3c mach_msg + 72 2 CoreFoundation
0x0000000184acfce4 CFRunLoopServiceMachPort + 196 3
CoreFoundation 0x0000000184acd8b0 __CFRunLoopRun + 1424 4 CoreFoundation 0x00000001849ee2d8 CFRunLoopRunSpecific + 436 5 Foundation
0x00000001854166e4 -[NSRunLoop+ 50916 (NSRunLoop) runMode:beforeDate:] + 304 6 Foundation
0x000000018546862c -[NSRunLoop+ 386604 (NSRunLoop) run] + 88 7 My App Test 0x000000010225b108 0x102180000 + 897288 8
Foundation 0x0000000185517860 __NSThread__start
+ 996 9 libsystem_pthread.dylib 0x000000018475432c _pthread_body + 308 10 libsystem_pthread.dylib 0x00000001847541f8 _pthread_body + 0 11 libsystem_pthread.dylib
0x0000000184752c38 thread_start + 4

Thread 6 name: com.apple.NSURLConnectionLoader Thread 6: 0
libsystem_kernel.dylib 0x0000000184620bc4 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x0000000184620a3c mach_msg + 72 2
CoreFoundation 0x0000000184acfce4 CFRunLoopServiceMachPort + 196 3 CoreFoundation 0x0000000184acd8b0 __CFRunLoopRun + 1424 4 CoreFoundation
0x00000001849ee2d8 CFRunLoopRunSpecific + 436 5 CFNetwork
0x0000000185157b40 +[NSURLConnection+ 715584 (Loader) _resourceLoadLoop:] + 404 6 Foundation 0x0000000185517860 __NSThread__start
+ 996 7
libsystem_pthread.dylib 0x000000018475432c _pthread_body + 308 8 libsystem_pthread.dylib 0x00000001847541f8 _pthread_body + 0 9 libsystem_pthread.dylib 0x0000000184752c38 thread_start + 4

Thread 0 crashed with ARM Thread State (64-bit): x0: 0x00000001c4227c60 x1: 0x000000018eca2db2 x2: 0x0000000000000000 x3: 0x000000010637e8d0 x4: 0x0000000000000002 x5: 0x0000000000000020 x6: 0x00000001021e82e8 x7: 0x0000000000000b70 x8: 0x0000000000000000 x9: 0x0000000000000000 x10: 0x01446b0101446b80 x11: 0x0000000001446b01 x12: 0x0000000001446a00 x13: 0x0000000000000001 x14: 0x0000000000000000 x15: 0x01446b0101446bc0 x16: 0x0000000000000000 x17: 0x0000000102bec19c x18: 0x0000000000000000 x19: 0x00000001c4227c60 x20: 0x00000001c4227c60 x21: 0x00000001c4227c60 x22: 0x00000000000000d0 x23: 0x00000000000001f0 x24: 0x0000000000000008 x25: 0x00000001c4107740 x26: 0x00000001c40ca6b0 x27: 0x00000001c4093330
x28: 0x00000001b3f8f000 fp: 0x000000016dc7ce40 lr: 0x0000000102bec1b0 sp: 0x000000016dc7ce30 pc: 0x0000000102bdf278 cpsr: 0x20000000

EDIT: After @FranticRock s' answer. When I delete [UINavigationBar setTitleTextAttributes:] detail class can open but none of the items (title, back button or any cell) is shown. They are all empty and I'm still getting leaks.

Here is the controller class where where I write [UINavigationBar setTitleTextAttributes:]

class WelcomeViewController: BaseViewController {

let bgView = UIView()
let backgroundImage = UIImageView()

let logoImage: UIImageView = {
    let i = UIImageView()
    i.image = UIImage(named: "full_logo")
    i.contentMode = .scaleAspectFit
    return i
}()

let welcomeLabel : UILabel = {
    let l = UILabel()
    l.font = Fonts.font.withSize(24)
    l.textColor = UIColor.white
    l.textAlignment = .center
    l.numberOfLines = 0
    l.sizeToFit()
    return l
}()

let loginLbl: UILabel = {
    let l = UILabel()
    l.font = Fonts.font.withSize(13)
    l.textColor = UIColor.white
    l.textAlignment = .center
    l.numberOfLines = 0
    l.sizeToFit()
    return l
}()

let adminBtn: UIButton = {
    let b = UIButton()
    b.backgroundColor = Color.Common.buttonColor
    b.layer.cornerRadius = 6.0
    return b
}()

let userBtn: UIButton = {
    let b = UIButton()
    b.backgroundColor = Color.Common.buttonColor
    b.layer.cornerRadius = 6.0
    return b
}()

lazy var supportedServicesView = WelcomeScreenButtonView(text: getLabelText(key: CMSKeys.CMS_LBL_SUPPORTEDSERVICES), imageName: "phone")
lazy var incidentView = WelcomeScreenButtonView(text: getLabelText(key: CMSKeys.CMS_LBL_INCIDENT), imageName: "phone")
lazy var contactUsView = WelcomeScreenButtonView(text: getLabelText(key:CMSKeys.CMS_LBL_CONTACT), imageName: "phone")
lazy var moreView = WelcomeScreenButtonView(text: getLabelText(key:CMSKeys.CMS_LBL_MORE), imageName: "wdiger")

lazy var emergencyBtn = SendButton(text: "Button")

let firstStackView = UIStackView()
let secondStackView = UIStackView()
let thirdStackView = UIStackView()

let btnStackView = UIStackView()

override func viewDidLoad() {
    super.viewDidLoad()
    self.setPageID()
    designUI()
}

override func viewDidAppear(_ animated: Bool) {
    if(AppContext.instance.comesFromURL != nil){
        comesFromURL()
    }
}
override func viewWillAppear(_ animated: Bool) {
    if(analyticsName != nil){
        self.sendDataToGA()
    }
}

override func viewDidLayoutSubviews() {

    bgView.anchor(self.thirdStackView.topAnchor, left: self.view.leftAnchor, bottom: self.view.bottomAnchor, right: self.view.rightAnchor, topConstant: 40, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)

    let margins = view.layoutMarginsGuide
    thirdStackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor,constant: 5).isActive = true
    thirdStackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor,constant: -5).isActive = true
    thirdStackView.bottomAnchor.constraint(equalTo: self.emergencyBtn.topAnchor, constant: -10).isActive = true
    thirdStackView.heightAnchor.constraint(equalTo: thirdStackView.widthAnchor, multiplier: 0.77).isActive = true

    emergencyBtn.anchor(nil, left: self.view.leftAnchor, bottom: self.bottomLayoutGuide.topAnchor, right: self.view.rightAnchor, topConstant: 10, leftConstant: 20, bottomConstant: 20, rightConstant: 20, widthConstant: 0, heightConstant: 48)
    if #available(iOS 11.0, *) {
        logoImage.anchor(self.view.safeAreaLayoutGuide.topAnchor, left: self.view.leftAnchor, bottom: nil, right: self.view.rightAnchor, topConstant: 40, leftConstant: 80, bottomConstant: 0, rightConstant: 80, widthConstant: 0, heightConstant: 0)
    } else {
        logoImage.anchor(self.view.topAnchor, left: self.view.leftAnchor, bottom: nil, right: self.view.rightAnchor, topConstant: 40, leftConstant: 80, bottomConstant: 0, rightConstant: 80, widthConstant: 0, heightConstant: 0)
        // Fallback on earlier versions
    }
    logoImage.anchorCenterXToSuperview()
    let welcomeLblHeight = heightForView(text: "Welcome", font: welcomeLabel.font, width: self.view.bounds.width)
    let loginLblHeight = heightForView(text: "Please Log In", font: loginLbl.font, width: self.view.bounds.width)
    welcomeLabel.anchor(self.logoImage.bottomAnchor, left: self.view.leftAnchor, bottom: nil, right: self.view.rightAnchor, topConstant: 0, leftConstant: 50, bottomConstant: 0, rightConstant: 50, widthConstant: 0, heightConstant: welcomeLblHeight)
    loginLbl.anchor(self.welcomeLabel.bottomAnchor, left: self.view.leftAnchor, bottom: nil, right: self.view.rightAnchor, topConstant: 10, leftConstant: 50, bottomConstant: 0, rightConstant: 50, widthConstant: 0, heightConstant: loginLblHeight)
    btnStackView.anchor(nil, left: self.view.leftAnchor, bottom: self.thirdStackView.topAnchor, right: self.view.rightAnchor, topConstant: 0, leftConstant: 20, bottomConstant: 20, rightConstant: 20, widthConstant: 0, heightConstant: 50)

    backgroundImage.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - self.bgView.frame.height)
}

private func designUI(){
    self.view.translatesAutoresizingMaskIntoConstraints = true
    backgroundImage.image = UIImage(named: "background.png")
    backgroundImage.contentMode = .scaleAspectFill
    self.view.insertSubview(backgroundImage, at: 0)

    bgView.backgroundColor = Color.Common.welcomeScreenBackgroundColor
    self.view.insertSubview(bgView, at: 1)
    view.addSubview(logoImage)
    welcomeLabel.text = getLabelText(key: CMSKeys.CMS_LBL_WELCOME)
    view.addSubview(welcomeLabel)
    loginLbl.text = getLabelText(key: CMSKeys.CMS_LBL_LOGIN)
    view.addSubview(loginLbl)

    adminBtn.backgroundColor = Color.Common.adminGreen
    adminBtn.setTitle(getLabelText(key: CMSKeys.CMS_BTN_ADMIN), for: .normal)
    adminBtn.addTarget(self, action: #selector(adminBtnTapped(_:)), for: .touchUpInside)

    userBtn.backgroundColor = Color.Common.userGreen
    userBtn.setTitle(getLabelText(key: CMSKeys.CMS_BTN_USER), for: .normal)
    userBtn.addTarget(self, action: #selector(userBtnTapped(_:)), for: .touchUpInside)

    btnStackView.axis  = UILayoutConstraintAxis.horizontal
    btnStackView.distribution = UIStackViewDistribution.fillEqually
    btnStackView.alignment = UIStackViewAlignment.fill
    btnStackView.spacing = 10.0
    btnStackView.addArrangedSubview(adminBtn)
    btnStackView.addArrangedSubview(userBtn)
    btnStackView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(btnStackView)

    firstStackView.axis  = UILayoutConstraintAxis.vertical
    firstStackView.distribution = UIStackViewDistribution.fillEqually
    firstStackView.alignment = UIStackViewAlignment.fill
    firstStackView.spacing = 10.0
    firstStackView.addArrangedSubview(supportedServicesView)
    firstStackView.addArrangedSubview(contactUsView)
    firstStackView.translatesAutoresizingMaskIntoConstraints = false

    secondStackView.axis  = UILayoutConstraintAxis.vertical
    secondStackView.distribution = UIStackViewDistribution.fillEqually
    secondStackView.alignment = UIStackViewAlignment.fill
    secondStackView.spacing = 10.0
    secondStackView.addArrangedSubview(incidentView)
    secondStackView.addArrangedSubview(moreView)
    secondStackView.translatesAutoresizingMaskIntoConstraints = false

    thirdStackView.axis = UILayoutConstraintAxis.horizontal
    thirdStackView.distribution = UIStackViewDistribution.fillEqually
    thirdStackView.alignment = UIStackViewAlignment.fill
    thirdStackView.spacing = 10.0
    thirdStackView.addArrangedSubview(firstStackView)
    thirdStackView.addArrangedSubview(secondStackView)
    thirdStackView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(thirdStackView)

    //View Tap Gestures
    let tapSupportedServices = UITapGestureRecognizer(target: self, action: #selector(self.tapSupportedServices(_:)))
    supportedServicesView.addGestureRecognizer(tapSupportedServices)
    supportedServicesView.isUserInteractionEnabled = true

    let tapIncidentView = UITapGestureRecognizer(target: self, action: #selector(self.tapIncident(_:)))
    incidentView.addGestureRecognizer(tapIncidentView)
    incidentView.isUserInteractionEnabled = true

    let tapContactUs = UITapGestureRecognizer(target: self, action: #selector(self.tapContactUs(_:)))
    contactUsView.addGestureRecognizer(tapContactUs)
    contactUsView.isUserInteractionEnabled = true

    let tapMoreView = UITapGestureRecognizer(target: self, action: #selector(self.tapMore(_:)))
    moreView.addGestureRecognizer(tapMoreView)
    moreView.isUserInteractionEnabled = true

    emergencyBtn.layer.cornerRadius = 6.0
    emergencyBtn.addTarget(self, action: #selector(emergenyBtnTapped(_:)), for: .touchUpInside)
    self.view.addSubview(emergencyBtn)

}

@objc func tapSupportedServices(_ sender: UITapGestureRecognizer) {
    let linkingVC = SupportedServicesFirstViewController()
    let controller = createNavController(title: "Services", viewController: linkingVC)
    self.present(controller, animated: true)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

private func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()

    return label.frame.height
}

//Gets a Title and a ViewController then returns a UINavigationController with attributes
private func createNavController(title: String, viewController: UIViewController) -> UINavigationController {
    viewController.view.backgroundColor = UIColor(red:0.87, green:0.87, blue:0.87, alpha:1.0)
    let navController = UINavigationController(rootViewController: viewController)
    navController.navigationBar.topItem?.title = title
    navController.navigationBar.barTintColor = Color.NavigationBar.tintColor
    navController.navigationBar.tintColor = UIColor.white
    //Fix: Leak
    navController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: Color.NavigationBar.textColor]

    return navController
}

private func removeViews(){
    self.emergencyBtn.removeFromSuperview()
    self.incidentView.removeFromSuperview()
    self.moreView.removeFromSuperview()
    self.supportedServicesView.removeFromSuperview()
    self.contactUsView.removeFromSuperview()
}
deinit {
    print("Welcome Deinited")
    removeViews()
}
}
2
In all probability the reason you crash when profiling but not normally is that profiling uses a Release build.matt
Profiling in release isnt it the right way?Emre Önder
Absolutely yes. But the point is that this is evidently bringing out a threading problem that a Debug build doesn't; otherwise you'd see the issue when you just build and run from Xcode. So what I'm saying is, try changing the scheme so that build-and-run uses a Release build, and see if I'm right (i.e. you crash). If so, this has nothing to do with Instruments, and now your question becomes just a duplicate of all the other threading-issue EXC_BAD_ACCESS crash questions. But if I'm wrong, then something about the Leaks instrument particularly may be at fault (and you should file a bug).matt
EXC_BAD_ACCESS : Maybe its cause sth was freed before use because there was no strong reference to it? I don‘t know whether self.present(..) holds a strong reference afterwards. Just a shot in the dark though. UINavigationController deiniting and taking the UINavigationBar with it is definietly possible. Maybe derive UINavigationController, add a deinit with a print-line and see whether it deinits too early.Fabian

2 Answers

4
votes

In the first stack trace, there is code related to: [UINavigationBar setTitleTextAttributes:]
It's trying to customize the navigation bar by setting text attributes on the title. Are you doing that? Can you try commenting that out, and see if the problem goes away?

Technically what you have is not a memory leak. You are accessing a deallocated object. One other thing you can do is enable Zombie Objects, on the scheme which you are running, and see if you can get info on which object got deallocated.

Now if none of the stack traces above lead you to any of the code you directly wrote, and you say that you used the Memory Debug Graph tool already and did not find any strong references to any objects you are checking for leaks, I would use a more creative approach here to find the problem. The approach I often use is elimination. Start commenting out large parts of your controller, until you are left with just the empty shell. Each time, you can cut the code in half (log performance), and re-test which part of the code references the object which was deallocated.

Obviously since normal app operation doesn't result in a Bad Access Exception, it's likely related to XCode / Instruments internals, however the setTitleTextAttributes above looks suspicious, and I would first try to narrow down whether the issue is related to the Navigation Bar. Are you doing anything strange with the navigation hierarchy or customization of your navbar UI?

Also check whether other instances of that same View Controller exist in memory from previous navigation events / instances... It sounds like a UI object is getting dealloced, and then being updated by an async process later.

Also override your deinit { }. method and put a print statement inside, to detect all related objects being deallocated. This will help narrow down, which controller is being deallocated and accessed later.

Does it occur on all iOS Version / Device models or specific ones only?

0
votes

There are two issues being raised by the question. The first is why profiling is broken, and the second is why your application has a use-after-free issue.

@FranicRock has offered great suggestions on the second issue.

My suggestion for the profiling problem is to try a workaround. If your application can be compiled with the (as of writing) Beta Xcode 10.0 then you can go into Edit Schema (Command-<) and in the Diagnostics Tab for your Run action, Click on Logging Malloc Stack with sub-option All Allocation and Free History. Then you can:

  1. Run your app in the simulator.
  2. Press the memory graph button in the debugger area (8th icon which looks like three circles joined together)
  3. Do File->Export Memory Graph.

You can either study the memory graph yourself or put it in a public location like Pastebin for others to provide insights. Apple have an informative video on this new approach: WWDC-2018-416-Memory-Deep-Dive