简体   繁体   English

在 UIPickerView 上设置 selectRow() 时出现越界异常

[英]Beyond bounds exception when setting selectRow() on UIPickerView

I have a UIPicker view and which loads an array of Ints as its data source.我有一个 UIPicker 视图,它加载了一个 Ints 数组作为其数据源。 Selecting a row works fine, however when the app loads I want to have it display a specific item that is read from disk.选择一行可以正常工作,但是当应用程序加载时,我希望它显示从磁盘读取的特定项目。

Right now I'm just trying to pass in a specific row number as a raw int but at load its throwing an out of bounds error.现在,我只是试图将特定的行号作为原始 int 传递,但在加载时会抛出越界错误。 My guess is that it's trying to select the row before it has loaded its data source but I'm not sure how to fix this.我的猜测是它试图在加载其数据源之前选择该行,但我不知道如何解决这个问题。

My main class looks like this:我的主要课程如下所示:

class ViewController: UIViewController {
    let durations = Array(15...40)
    override func viewDidLoad() {
        super.viewDidLoad()
        durationPickerOut.dataSource  = self
        durationPickerOut.delegate = self
        durationPickerOut.selectRow(1, inComponent: 1, animated: false) // This is throwing the error
    }

// MARK extensions
extension ViewController: UIPickerViewDataSource{
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return durations.count
    }
}
extension ViewController: UIPickerViewDelegate{
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        String(durations[row])
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        cycleDuration = durations[row]
    }
    
}

Once I can select an arbitrary hard coded row then I'll switch it to something dynamic but right now I just want to be able to set it to select a given row.一旦我可以选择任意硬编码的行,然后我会将其切换为动态的,但现在我只想能够将其设置为选择给定的行。 The error thrown is this:抛出的错误是这样的:

 *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001803f3d70 __exceptionPreprocess + 236
    1   libobjc.A.dylib                     0x000000018019814c objc_exception_throw + 56
    2   CoreFoundation                      0x00000001804793b4 -[__NSCFString characterAtIndex:].cold.1 + 0
    3   CoreFoundation                      0x00000001802ebf38 -[__NSArrayM getObjects:range:] + 0
    4   UIKitCore                           0x0000000184d1e384 -[UIPickerView _selectRow:inComponent:animated:notify:] + 120
    5   MyApp               0x000000010263aff8 $s015MyApp_Privacy_A014ViewControllerC11viewDidLoadyyF + 2496
    6   MyApp               0x000000010263b7a4 $s015MyApp_Privacy_A014ViewControllerC11viewDidLoadyyFTo + 36
    7   UIKitCore                           0x00000001846342ec -[UIViewController _sendViewDidLoadWithAppearanceProxyObjectTaggingEnabled] + 104
    8   UIKitCore                           0x0000000184638898 -[UIViewController loadViewIfRequired] + 1020
    9   UIKitCore                           0x0000000184638c64 -[UIViewController view] + 28
    10  UIKitCore                           0x0000000184dca34c -[UIWindow addRootViewControllerViewIfPossible] + 176
    11  UIKitCore                           0x0000000184dc9b7c -[UIWindow _updateLayerOrderingAndSetLayerHidden:actionBlock:] + 224
    12  UIKitCore                           0x0000000184dca9a4 -[UIWindow _setHidden:forced:] + 252
    13  UIKitCore                           0x0000000184ddb3b4 -[UIWindow _mainQueue_makeKeyAndVisible] + 52
    14  UIKitCore                           0x0000000185021a20 -[UIWindowScene _makeKeyAndVisibleIfNeeded] + 200
    15  UIKitCore                           0x00000001841cc594 +[UIScene _sceneForFBSScene:create:withSession:connectionOptions:] + 1428
    16  UIKitCore                           0x0000000184d8a408 -[UIApplication _connectUISceneFromFBSScene:transitionContext:] + 1268
    17  UIKitCore                           0x0000000184d8a8b0 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 312
    18  UIKitCore                           0x000000018485dbb4 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 360
    19  FrontBoardServices                  0x0000000186166718 -[FBSScene _callOutQueue_agent_didCreateWithTransitionContext:completion:] + 412
    20  FrontBoardServices                  0x0000000186192620 __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke.180 + 100
    21  FrontBoardServices                  0x0000000186174d00 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 232
    22  FrontBoardServices                  0x000000018619223c __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke + 312
    23  libdispatch.dylib                   0x00000001029f9b94 _dispatch_client_callout + 16
    24  libdispatch.dylib                   0x00000001029fce88 _dispatch_block_invoke_direct + 256
    25  FrontBoardServices                  0x00000001861b8074 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 40
    26  FrontBoardServices                  0x00000001861b7f4c -[FBSSerialQueue _targetQueue_performNextIfPossible] + 176
    27  FrontBoardServices                  0x00000001861b80a4 -[FBSSerialQueue _performNextFromRunLoopSource] + 24
    28  CoreFoundation                      0x0000000180362234 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
    29  CoreFoundation                      0x0000000180362134 __CFRunLoopDoSource0 + 204
    30  CoreFoundation                      0x0000000180361520 __CFRunLoopDoSources0 + 348
    31  CoreFoundation                      0x000000018035ba18 __CFRunLoopRun + 744
    32  CoreFoundation                      0x000000018035b218 CFRunLoopRunSpecific + 572
    33  GraphicsServices                    0x000000018c25f60c GSEventRunModal + 160
    34  UIKitCore                           0x0000000184d88a98 -[UIApplication _run] + 992
    35  UIKitCore                           0x0000000184d8d634 UIApplicationMain + 112
    36  libswiftUIKit.dylib                 0x00000001b6946224 $s5UIKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSgSSSgAJtF + 100
    37  MyApp               0x000000010263fa04 $sSo21UIApplicationDelegateP5UIKitE4mainyyFZ + 104
    38  MyApp               0x000000010263f98c $s015MyApp_Privacy_A011AppDelegateC5$mainyyFZ + 44
    39  MyApp               0x000000010263fa88 main + 28
    40  dyld                                0x0000000102975cd8 start_sim + 20
    41  ???                                 0x00000001027bd0f4 0x0 + 4336636148
    42  ???                                 0x464b800000000000 0x0 + 5065282943396610048
)
libc++abi: terminating with uncaught exception of type NSException
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/squidgylabs/Library/Developer/Xcode/DerivedData/MyApp_Privacy_MyApp-cnetykaxqecqzpatuvwawzyuqfwr/Build/Products/Debug-iphonesimulator:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libBacktraceRecording.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libMainThreadChecker.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib DYLD_FRAMEWORK_PATH=/Users/squidgylabs/Library/Developer/Xcode/DerivedData/MyApp_Privacy_MyApp-cnetykaxqecqzpatuvwawzyuqfwr/Build/Products/Debug-iphonesimulator
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
terminating with uncaught exception of type NSException
CoreSimulator 802.6.1 - Device: iPhone 13 Pro (EC065371-1DB1-48A9-A629-365188E36AAE) - Runtime: iOS 15.5 (19F70) - DeviceType: iPhone 13 Pro
(lldb)  *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001803f3d70 __exceptionPreprocess + 236
    1   libobjc.A.dylib                     0x000000018019814c objc_exception_throw + 56
    2   CoreFoundation                      0x00000001804793b4 -[__NSCFString characterAtIndex:].cold.1 + 0
    3   CoreFoundation                      0x00000001802ebf38 -[__NSArrayM getObjects:range:] + 0
    4   UIKitCore                           0x0000000184d1e384 -[UIPickerView _selectRow:inComponent:animated:notify:] + 120
    5   MyApp               0x000000010263aff8 $s015MyApp_Privacy_A014ViewControllerC11viewDidLoadyyF + 2496
    6   MyApp               0x000000010263b7a4 $s015MyApp_Privacy_A014ViewControllerC11viewDidLoadyyFTo + 36
    7   UIKitCore                           0x00000001846342ec -[UIViewController _sendViewDidLoadWithAppearanceProxyObjectTaggingEnabled] + 104
    8   UIKitCore                           0x0000000184638898 -[UIViewController loadViewIfRequired] + 1020
    9   UIKitCore                           0x0000000184638c64 -[UIViewController view] + 28
    10  UIKitCore                           0x0000000184dca34c -[UIWindow addRootViewControllerViewIfPossible] + 176
    11  UIKitCore                           0x0000000184dc9b7c -[UIWindow _updateLayerOrderingAndSetLayerHidden:actionBlock:] + 224
    12  UIKitCore                           0x0000000184dca9a4 -[UIWindow _setHidden:forced:] + 252
    13  UIKitCore                           0x0000000184ddb3b4 -[UIWindow _mainQueue_makeKeyAndVisible] + 52
    14  UIKitCore                           0x0000000185021a20 -[UIWindowScene _makeKeyAndVisibleIfNeeded] + 200
    15  UIKitCore                           0x00000001841cc594 +[UIScene _sceneForFBSScene:create:withSession:connectionOptions:] + 1428
    16  UIKitCore                           0x0000000184d8a408 -[UIApplication _connectUISceneFromFBSScene:transitionContext:] + 1268
    17  UIKitCore                           0x0000000184d8a8b0 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 312
    18  UIKitCore                           0x000000018485dbb4 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 360
    19  FrontBoardServices                  0x0000000186166718 -[FBSScene _callOutQueue_agent_didCreateWithTransitionContext:completion:] + 412
    20  FrontBoardServices                  0x0000000186192620 __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke.180 + 100
    21  FrontBoardServices                  0x0000000186174d00 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 232
    22  FrontBoardServices                  0x000000018619223c __94-[FBSWorkspaceScenesClient createWithSceneID:groupID:parameters:transitionContext:completion:]_block_invoke + 312
    23  libdispatch.dylib                   0x00000001029f9b94 _dispatch_client_callout + 16
    24  libdispatch.dylib                   0x00000001029fce88 _dispatch_block_invoke_direct + 256
    25  FrontBoardServices                  0x00000001861b8074 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 40
    26  FrontBoardServices                  0x00000001861b7f4c -[FBSSerialQueue _targetQueue_performNextIfPossible] + 176
    27  FrontBoardServices                  0x00000001861b80a4 -[FBSSerialQueue _performNextFromRunLoopSource] + 24
    28  CoreFoundation                      0x0000000180362234 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
    29  CoreFoundation                      0x0000000180362134 __CFRunLoopDoSource0 + 204
    30  CoreFoundation                      0x0000000180361520 __CFRunLoopDoSources0 + 348
    31  CoreFoundation                      0x000000018035ba18 __CFRunLoopRun + 744
    32  CoreFoundation                      0x000000018035b218 CFRunLoopRunSpecific + 572
    33  GraphicsServices                    0x000000018c25f60c GSEventRunModal + 160
    34  UIKitCore                           0x0000000184d88a98 -[UIApplication _run] + 992
    35  UIKitCore                           0x0000000184d8d634 UIApplicationMain + 112
    36  libswiftUIKit.dylib                 0x00000001b6946224 $s5UIKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSgSSSgAJtF + 100
    37  MyApp               0x000000010263fa04 $sSo21UIApplicationDelegateP5UIKitE4mainyyFZ + 104
    38  MyApp               0x000000010263f98c $s015MyApp_Privacy_A011AppDelegateC5$mainyyFZ + 44
    39  MyApp               0x000000010263fa88 main + 28
    40  dyld                                0x0000000102975cd8 start_sim + 20
    41  ???                                 0x00000001027bd0f4 0x0 + 4336636148
    42  ???                                 0x464b800000000000 0x0 + 5065282943396610048
)
libc++abi: terminating with uncaught exception of type NSException
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/squidgylabs/Library/Developer/Xcode/DerivedData/MyApp_Privacy_MyApp-cnetykaxqecqzpatuvwawzyuqfwr/Build/Products/Debug-iphonesimulator:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libBacktraceRecording.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libMainThreadChecker.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib DYLD_FRAMEWORK_PATH=/Users/squidgylabs/Library/Developer/Xcode/DerivedData/MyApp_Privacy_MyApp-cnetykaxqecqzpatuvwawzyuqfwr/Build/Products/Debug-iphonesimulator
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
terminating with uncaught exception of type NSException
CoreSimulator 802.6.1 - Device: iPhone 13 Pro (EC065371-1DB1-48A9-A629-365188E36AAE) - Runtime: iOS 15.5 (19F70) - DeviceType: iPhone 13 Pro
(lldb) MyApp

它是从零开始的,这意味着行从 0 开始到 < N(N 是行数)对于组件相同

durationPickerOut.selectRow(0, inComponent: 0, animated: false)  

It is as simple as UITableView behaviour, while we are supplying the data source for both UITableView and UIPickerView we use Int value which defines the number of sections, rows to the UITableView and Columns, row to the UIPickerView .它就像UITableView的行为一样简单,当我们为UITableViewUIPickerView提供数据源时,我们使用Int值来定义部分的数量, UITableView的行数和UIPickerView的行数。

In your case working with UIPickerView , you told one column is required在您使用UIPickerView的情况下,您告诉我们需要一列

extension ViewController: UIPickerViewDataSource{
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return durations.count
    }
}

Here is the main focus, while accessing the component and row it will alway starts from 0,1,2...(N-1)这是主要焦点,在访问componentrow ,它将始终从0,1,2...(N-1)开始

So, now you can fix this by changing the default selecting column to 0 as you are supplying one column因此,现在您可以通过在提供一列时将默认选择列更改为0来解决此问题

durationPickerOut.selectRow(1, inComponent: 0, animated: false) //<<<<! FIX

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM