Opening a new window on a different storyboard - swift

I am developing an OS X app with storyboards. I get the Preview.storyboard with an Entry Point on an anonymous window with a custom ViewController. In the AppDelegate class, I get the following function.
func newPreviewWindow(sender: AnyObject) {
let storyboard = NSStoryboard.init(name: "Preview", bundle: nil)
let initialController = storyboard.instantiateInitialController()
initialController!.showWindow(nil)
initialController!.makeKeyAndOrderFront(nil)
}
When running the code, the window shows, but I get the following exception:
2016-08-11 10:27:12.434 MyApp[1090:290439] -[NSWindowController makeKeyAndOrderFront:]: unrecognized selector sent to instance 0x60000008c350
2016-08-11 10:27:12.434 MyApp[1090:290439] -[NSWindowController makeKeyAndOrderFront:]: unrecognized selector sent to instance 0x60000008c350
2016-08-11 10:27:12.440 MyApp[1090:290439] (
0 CoreFoundation 0x00007fff926284f2 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff97c0ef7e objc_exception_throw + 48
2 CoreFoundation 0x00007fff926921ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00007fff92598571 ___forwarding___ + 1009
4 CoreFoundation 0x00007fff925980f8 _CF_forwarding_prep_0 + 120
5 MyApp 0x0000000100005617
...
Based on the exception message and search on Google and StackOverflow, I tried sending a Selector to the makeKeyAndOrderFront function this way :
func newPreviewWindow(sender: AnyObject) {
let storyboard = NSStoryboard.init(name: "Preview", bundle: nil)
let initialController = storyboard.instantiateInitialController()
let selector = #selector(AppDelegate.newPreviewWindow(_:))
initialController!.showWindow(nil)
initialController!.makeKeyAndOrderFront(selector) // [A]
}
But then I get the following compile error on line [A]: Cannot call value of non-function type '((AnyObject?) -> Void)!'
How is the proper way to open the new window or to pass the Selector?
Thanks! :)

initialController!.makeKeyAndOrderFront(nil) is causing a problem because makeKeyAndOrderFront: is not an NSWindowController method - it belongs to NSWindow (hence the unrecognized selector error). Cast your initial controller to your NSWindowController subclass, then bring the window to the front via the controller's window property:
var windowController: NSWindowController!
#IBAction func showOtherWindow(sender: AnyObject) {
windowController = storyboard.instantiateInitialController() as! NSWindowController
windowController.window?.makeKeyAndOrderFront(nil)
}

Related

Need help understanding some swift MacOS crashes

I am trying to understand why the Preference panes for HSTracker (https://github.com/HearthSim/HSTracker/tree/2.1.10/HSTracker) are reporting crashes on the viewDidLoad method.
HSTracker
HSTracker.GeneralPreferences.viewDidLoad() -> () GeneralPreferences.swift:0
HSTracker
#objc HSTracker.GeneralPreferences.viewDidLoad() -> () <compiler-generated>:0
AppKit
-[NSViewController _sendViewDidLoad]
HSTracker
function signature specialization <Arg[0] = Owned To Guaranteed> of Preferences.PreferencesWindowController.init(preferencePanes: [Preferences.PreferencePane], style: Preferences.Preferences.Style, animated: Swift.Bool, hidesToolbarForSingleItem: Swift.Bool) -> Preferences.PreferencesWindowController PreferencesWindowController.swift:37
HSTracker
Preferences.PreferencesWindowController.init(preferencePanes: [Preferences.PreferencePane], style: Preferences.Preferences.Style, animated: Swift.Bool, hidesToolbarForSingleItem: Swift.Bool) -> Preferences.PreferencesWindowController <compiler-generated>:0
HSTracker
HSTracker.AppDelegate.preferences.getter : Preferences.PreferencesWindowController <compiler-generated>:0
HSTracker
#objc HSTracker.AppDelegate.openPreferences(Swift.AnyObject) -> () AppDelegate.swift:583
AppKit
-[NSApplication(NSResponder) sendAction:to:from:]
HSTracker
main AppDelegate.swift:21
0x0 + 0
Using atos, I decoded the crash location to the very first line on the method:
https://github.com/HearthSim/HSTracker/blob/2.1.10/HSTracker/UIs/Preferences/GeneralPreferences.swift#L32
notifyGameStart.state = Settings.notifyGameStart ? .on : .off
So why would it crash on that line, assuming all the IBOutlets are properly linked in the XIB file?
There is similarly strange crash when presenting a property sheet on this code:
newDeck = NewDeck(windowNibName: "NewDeck")
if let newDeck = newDeck {
newDeck.setDelegate(self)
newDeck.defaultClass = currentClass ?? nil
self.window!.beginSheet(newDeck.window!, completionHandler: nil)
}
The crash happens on the newDeck.window! forced unwrap.
I can use some insights on why these two crashes happen and how to avoid/fix them.

How to populate TableView cell from datasource? I am currently receiving error

I am trying to return an array of Geocoded Placemarks from Mapbox Geocoder to TableView cells, but I am receiving an error (assertion failure in UITableView and failed to obtain a cell). Am I doing something incorrectly with the delegate or index path? I am have looked at similar questions, but I am unable to solve it.
I am using a storyboard; I have triple checked the cell identifier in my storyboard to make sure it aligned to 'with identifier'.
EDIT: I was able to remove the error by changing 'cellForRowAt indexPath: NSIndexPath' to 'cellForRowAt indexPath: IndexPath'.
Now when I enter text into the SearchBar it is returning the array, but the cells are empty even with data. Empty Cells Picture
import UIKit
import MapboxGeocoder
class LocationSearchTable: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
var placemarkResults: [GeocodedPlacemark] = []
func forwardGeocoding(addressQuery: String) {
let geocoder = Geocoder(accessToken: "//OMITTED//")
let options = ForwardGeocodeOptions(query: addressQuery)
options.allowedScopes = [.address]
options.allowedISOCountryCodes = ["US"]
options.autocompletesQuery = true
let _ = geocoder.geocode(options) { (placemarks, attribution, error) in
guard let placemarks = placemarks, !placemarks.isEmpty else {
return
}
self.placemarkResults = placemarks
}
print(placemarkResults)
}
}
extension LocationSearchTable: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let searchBarText = searchController.searchBar.text else { return }
let _ = forwardGeocoding(addressQuery: searchBarText)
self.tableView.reloadData()
}
}
extension LocationSearchTable {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return placemarkResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let selectedItem = placemarkResults[indexPath.row].place
cell.textLabel?.text = selectedItem?.name
cell.detailTextLabel?.text = ""
return cell
}
}
2019-06-26 00:45:22.179129-0700 Ride Sharing App[91152:18783310] *** Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3698.103.12/UITableView.m:9655
2019-06-26 00:45:22.186549-0700 Ride Sharing App[91152:18783310] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (<UITableView: 0x7f8fb398e200; frame = (0 0; 414 896); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x6000018395c0>; layer = <CALayer: 0x60000161fca0>; contentOffset: {0, -144}; contentSize: {414, 44}; adjustedContentInset: {144, 0, 34, 0}>) failed to obtain a cell from its dataSource (<Ride_Sharing_App.LocationSearchTable: 0x7f8fb2d69660>)'
*** First throw call stack:
(
0 CoreFoundation 0x000000010e2196fb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x000000010b3b7ac5 objc_exception_throw + 48
2 CoreFoundation 0x000000010e219482 +[NSException raise:format:arguments:] + 98
3 Foundation 0x000000010ae05927 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 194
4 UIKitCore 0x0000000115f0799f -[UITableView _configureCellForDisplay:forIndexPath:] + 433
5 UIKitCore 0x0000000115f1a6bf -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 911
6 UIKitCore 0x0000000115f1ab65 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 73
7 UIKitCore 0x0000000115ee2d20 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2870
8 UIKitCore 0x0000000115f02e37 -[UITableView layoutSubviews] + 165
9 UIKitCore 0x00000001161af9c1 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1417
10 QuartzCore 0x000000010ec85eae -[CALayer layoutSublayers] + 173
11 QuartzCore 0x000000010ec8ab88 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 396
12 QuartzCore 0x000000010ec96ee4 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 72
13 QuartzCore 0x000000010ec063aa _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 328
14 QuartzCore 0x000000010ec3d584 _ZN2CA11Transaction6commitEv + 608
15 QuartzCore 0x000000010ec3dede _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 76
16 CoreFoundation 0x000000010e1800f7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
17 CoreFoundation 0x000000010e17a5be __CFRunLoopDoObservers + 430
18 CoreFoundation 0x000000010e17ac31 __CFRunLoopRun + 1505
19 CoreFoundation 0x000000010e17a302 CFRunLoopRunSpecific + 626
20 GraphicsServices 0x00000001112542fe GSEventRunModal + 65
21 UIKitCore 0x0000000115ce1ba2 UIApplicationMain + 140
22 Ride Sharing App 0x0000000108ac21ab main + 75
23 libdyld.dylib 0x000000010ca4c541 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
your problem could be because you're not setting the delegate & datasource.
so try this :
in your class:
class LocationSearchTable: UITableViewController, UITableViewDelegate, UITableViewDataSource {
//Then set the delegate and dataSource in ViewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
}
Also make sure you have an outlet for your TableView named tableView

Unable to find NIB in bundle only after adding an object to CoreData?

This has been stumping me for a few hours and after looking through all kinds of related questions, I can't seem to figure out an answer.
I am getting a strange NSInternalInconsistencyException error. The error states that it cannot load an NIB with the name CountTableViewController. However, when I first run the app (in both simulator and physical device), I can segue to that view controller just fine. It loads and looks just as it does in the Main.storyboard file. Then, when I navigate back and activate another view controller that loads some test data into the Core Data Stack that I am using, things go very wrong. Using breakpoints and console logs, I can see that the single object has been successfully added into the Core Data Stack. But, when I click on the CountTableViewController again, the app crashes with the following error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Could not load NIB in bundle: 'NSBundle <FILEPATH> (loaded)' with name
'CountTableViewController''
I have read through every related question I could find, here's a quick list of things I have already tried that were unsuccessful:
Check spelling/case of related files and any place they are referenced
(CountTableViewController.swift, CountTableViewCell.swift, CountReuseCell [reuse id])
Delete references to related files, re-drag into Xcode
Delete references to Main.storyboard and LaunchScreen.storyboard, re-drag into Xcode
Verify that every file is listed correctly under 'Compile Sources' in 'Build Phases' of Project
Verify that storyboards are listed correctly under 'Copy Bundle Resources' in 'Build Phases' of Project
Rewrite as a totally new view controller from scratch (still got same error)
I'm pretty sure it's CoreData related since that seems to be the only difference between when the view controller does and does not work, but I'm pretty new to Swift and iOS dev, so I could be way off target.
I have the stack trace that I will post below. I will try to post some concise parts of the code that I think will be helpful. Thank you in advance for your help!
StackTrace:
0 CoreFoundation 0x000000010721912b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000102a78f41 objc_exception_throw + 48
2 CoreFoundation 0x000000010728e245 +[NSException raise:format:] + 197
3 UIKit 0x00000001043fd098 -[UINib instantiateWithOwner:options:] + 501
4 UIKit 0x00000001040b2687 -[UITableView _dequeueReusableViewOfType:withIdentifier:] + 590
5 UIKit 0x0000000120c4f79d -[UITableViewAccessibility dequeueReusableCellWithIdentifier:] + 147
6 UIKit 0x00000001040b2b6b -[UITableView _dequeueReusableCellWithIdentifier:forIndexPath:usingPresentationValues:] + 148
7 UIKit 0x00000001040b2aa3 -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] + 89
8 UIKit 0x0000000120c4f8e0 -[UITableViewAccessibility dequeueReusableCellWithIdentifier:forIndexPath:] + 285
9 BSA Inventory Control 0x00000001018d35d6 _T021BSA_Inventory_Control24CountTableViewControllerC05tableF0So07UITableF4CellCSo0iF0C_10Foundation9IndexPathV12cellForRowAttF + 774
10 BSA Inventory Control 0x00000001018d3c4c _T021BSA_Inventory_Control24CountTableViewControllerC05tableF0So07UITableF4CellCSo0iF0C_10Foundation9IndexPathV12cellForRowAttFTo + 92
11 UIKit 0x00000001040ce484 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 778
12 UIKit 0x00000001040cea2a -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
13 UIKit 0x00000001040941f6 -[UITableView _updateVisibleCellsNow:isRecursive:] + 3031
14 UIKit 0x00000001040b62e6 -[UITableView layoutSubviews] + 176
15 UIKit 0x000000010403ea6d -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1439
CountTableViewController.swift
import UIKit
import CoreData
class CountTableViewController: UITableViewController {
let coreDataStack = CoreDataStack.shared
var moc: NSManagedObjectContext! = nil
var counts: [Count] = []
override func viewDidLoad() {
super.viewDidLoad()
moc = coreDataStack.viewContext
tableView.register(CountTableViewCell.self, forCellReuseIdentifier: "CountReuseCell")
let nib = UINib(nibName: "CountTableViewController", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "CountReuseCell")
}
func reload() {
counts = Count.items(for: moc, matching: nil, sortedBy: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reload()
tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CountReuseCell", for: indexPath) as? CountTableViewCell else {
fatalError("The dequeued cell is not an instance of CountTableViewCell")
}
let count = counts[indexPath.row]
cell.nameLabel.text = count.name
return cell
}
}
The CountTableViewCell.swift file is just a default Cocoa Touch Class with a subclass of UITableViewCell and a single outlet linking to the nameLabel in the storyboard.
A few quick afterthoughts... please let me know if there's any info you need that I didn't include here. I'm using a Core Data Stack Class and an extension adapted by a professor in an iOS dev class I took a year ago that provides the easy to use .items() functionality... I can also post that if you think that's causing any issues. This is so strange because I have another Core Data entity (Product instead of Count) using almost the exact same code that works perfectly. I can't seem to figure out what is different about this scenario...
Xcode Version 9.2 (9C40b), iOS Version 11.2 (15C107)
Just to wrap things up and hopefully help someone in the future, the issue seems to have been in these lines within the CountTableViewController.swift:
tableView.register(CountTableViewCell.self, forCellReuseIdentifier: "CountReuseCell")
let nib = UINib(nibName: "CountTableViewController", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "CountReuseCell")
As usual, it seems this was a mixture of reusing old code and copy/pasting. It's strange that this code seems to work fine in almost an identical scenario with the Product entity in the same project. Nevertheless, I removed the last two lines above, leaving me with only:
tableView.register(CountTableViewCell.self, forCellReuseIdentifier: "CountReuseCell")
Sure enough, the NSInternalInconsistencyException error was gone!
Last night, I was able to rewrite the CountTableViewController entirely programatically and it is working correctly, so I plan to use that for now. However, it is good to know what was causing this error for the future.
Thanks to #pbasdf for the comment/answer!

Address Book crash on iOS10

Selecting a contact from contact picker crashes the app in iOS10.0. Contacts picker is shown using ABPeoplePickerNavigationController like this:
let contactsPicker = ABPeoplePickerNavigationController()
contactsPicker.peoplePickerDelegate = self
self.presentViewController(contactsPicker, animated: true, completion: nil)
Here is the stack trace from crash log:
*** Terminating app due to uncaught exception 'CNPropertyNotFetchedException', reason: 'A property was not requested when contact was fetched.'
*** First throw call stack:
(
0 CoreFoundation 0x0000000105a1c34b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x00000001052cd21e objc_exception_throw + 48
2 CoreFoundation 0x0000000105a85265 +[NSException raise:format:] + 197
3 Contacts 0x000000010dc6d96f -[CNContact sectionForSortingByFamilyName] + 160
4 Contacts 0x000000010dc3e18e __55-[CNContact(iOSABCompatibility) overwritePerson:error:]_block_invoke + 44
5 CoreFoundation 0x00000001059ad2fd __53-[__NSArrayI enumerateObjectsWithOptions:usingBlock:]_block_invoke + 77
6 CoreFoundation 0x00000001059ad1df -[__NSArrayI enumerateObjectsWithOptions:usingBlock:] + 207
7 Contacts 0x000000010dc3e0f4 -[CNContact(iOSABCompatibility) overwritePerson:error:] + 240
8 Contacts 0x000000010dc3dfc0 -[CNContact(iOSABCompatibility) detachedPersonWithError:] + 46
9 AddressBookUI 0x00000001057bdd77 -[ABPeoplePickerNavigationController contactPicker:didSelectContact:] + 145
10 ContactsUI 0x0000000112396eb2 -[CNContactPickerViewController pickerDidSelectContact:property:] + 306
11 ContactsUI 0x000000011243ee6f -[CNContactPickerHostViewController pickerDidSelectContact:property:] + 95
12 ContactsUI 0x000000011243f5ec __71-[CNContactPickerExtensionHostContext pickerDidSelectContact:property:]_block_invoke + 66
I have already added NSContactsUsageDescription in the info.plist as discussed on Contact Address book crash on iOS 10 beta but that didn't help and I can't use CNContactPickerViewController as I need to support iOS8 devices.
Imran Raheem
From Erdekhayser's solution (Contact Address book crash on iOS 10 beta)
you can use this method to check CNContactPickerViewController is available?
if (NSClassFromString(#"CNContactPickerViewController")) {
// iOS 9, 10, use CNContactPickerViewController
CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];
picker.delegate = self;
picker.displayedPropertyKeys = #[CNContactPhoneNumbersKey];
[pr presentViewController:picker animated:YES completion:nil];
}else{
// iOS 8 Below, use ABPeoplePickerNavigationController
ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
picker.peoplePickerDelegate = self;
[pr presentViewController:picker animated:YES completion:nil];
}
The Address Book API was deprecated in iOS 9 in favor of the more object-oriented Contacts Framework.
Instead of using the ABPeoplePickerViewController, move to CNContactPickerViewController.
I was getting the same error, when I was trying to get an emailAddresses from CNContact of delegate method.
Initially, I initialize the contactpicker:
//MARK: Contact Action
#IBAction func getContactListAction(_ sender: Any) {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey]
vcObject.present(contactPicker, animated: true, completion: nil)
}
Delegate method:
//MAKE: Contact Delegate
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
picker.dismiss(animated: true, completion: nil)
let name = CNContactFormatter.string(from: contact, style: .fullName)
print(name!)
self.textfieldName.text = name!
for number in contact.phoneNumbers {
print("number ----\(number)")
let mobile = number.value.value(forKey: "digits") as? String
if (mobile?.count)! > 7 {
// your code goes here
print("mobile---\(String(describing: mobile))")
self.textfieldMobileNumber.text = mobile!
}
}
// this line couse the crash ---> print(contact.emailAddresses[0].value(forKey: "value") as! String)
}
I was accessing the email address without declaring in initialization.
Error -- Terminating app due to uncaught exception 'CNPropertyNotFetchedException', reason: 'A property was not requested when contact was fetched.'
CORRECT CODE FOR ACCESSING EMAIL ---
Xcode 10 . and 4.2
//MARK: Contact Action
#IBAction func getContactListAction(_ sender: Any) {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey,CNContactEmailAddressesKey] .
// <--- Here make declaration for accessing the required property from CNContact.
vcObject.present(contactPicker, animated: true, completion: nil)
}
//MAKE: Contact Delegate
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
picker.dismiss(animated: true, completion: nil)
let name = CNContactFormatter.string(from: contact, style: .fullName)
print(name!)
self.textfieldName.text = name!
for number in contact.phoneNumbers {
print("number ----\(number)")
let mobile = number.value.value(forKey: "digits") as? String
if (mobile?.count)! > 7 {
// your code goes here
print("mobile---\(String(describing: mobile))")
self.textfieldMobileNumber.text = mobile!
}
}
// print(contact.emailAddresses[0].value.value(forKey: "labelValuePair") as! String)
for email in contact.emailAddresses {
print("number ----\(email)")
let eml = email.value(forKey: "value") as? String
print("eml --\(eml!)")
}
}

Xcode 7.2 and NSTimer throws uncaught exception

Here is the code:
import UIKit
class ViewController: UIViewController {
var clickNumber:Int = 0
#IBOutlet weak var CountLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
CountLabel.text = "0"
let interval: Double = 60/120*4
var metronomeTimer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "metronomeFunc:", userInfo: nil, repeats: true)
func metronomeFunc(timer:NSTimer) {
CountLabel.text = String(clickNumber)
clickNumber = clickNumber+1
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I don't know why, but on my new computer this simple thing doesn't work.
Here is what it gives me as a error:
2016-02-07 16:45:19.683 Move And Play[14743:2005023] -[Move_And_Play.ViewController metronomeFunc:]: unrecognized selector sent to instance 0x7f8c0a435c20
2016-02-07 16:45:19.695 Move And Play[14743:2005023] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Move_And_Play.ViewController metronomeFunc:]: unrecognized selector sent to instance 0x7f8c0a435c20'
*** First throw call stack:
(
0 CoreFoundation 0x000000010730ee65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010904edeb objc_exception_throw + 48
2 CoreFoundation 0x000000010731748d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010726490a ___forwarding___ + 970
4 CoreFoundation 0x00000001072644b8 _CF_forwarding_prep_0 + 120
5 Foundation 0x00000001076f40d1 __NSFireTimer + 83
6 CoreFoundation 0x000000010726ec84 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
7 CoreFoundation 0x000000010726e831 __CFRunLoopDoTimer + 1089
8 CoreFoundation 0x0000000107230241 __CFRunLoopRun + 1937
9 CoreFoundation 0x000000010722f828 CFRunLoopRunSpecific + 488
10 GraphicsServices 0x000000010bba3ad2 GSEventRunModal + 161
11 UIKit 0x0000000107b2b610 UIApplicationMain + 171
12 Move And Play 0x0000000106e2c17d main + 109
13 libdyld.dylib 0x0000000109b8592d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
It always worked before on my old computer with old version of xCode
Methods conforming to the target / selector pattern must be declared on the top level of the class.
class ViewController: UIViewController {
...
override func viewDidLoad() {
super.viewDidLoad()
CountLabel.text = "0"
let interval: Double = 2.0 // 60/120*4
var metronomeTimer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "metronomeFunc:", userInfo: nil, repeats: true)
}
func metronomeFunc(timer:NSTimer) {
CountLabel.text = String(clickNumber)
clickNumber = clickNumber+1
}
...
}
It certainly did not work on your old computer with the nested syntax.