2014-06-11 3 views
7

Мысль, что я попробую свою руку при разработке iOS с момента объявления Swift/ios8, и у меня возникнут проблемы с созданием базового tableView для сборки.XCode6/Swift: непризнанный селектор, отправленный в экземпляр

В настоящее время получают следующие сообщения об ошибках при загрузке приложения в симуляторе (Xcode говорит строить не завершится):

2014-06-11 13:40:56.173 firstapp[2217:85843] -[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0xb20fcf0 
2014-06-11 13:40:56.180 firstapp[2217:85843] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0xb20fcf0' 
*** First throw call stack: 
(
    0 CoreFoundation      0x00452916 __exceptionPreprocess + 182 
    1 libobjc.A.dylib      0x01da28d9 objc_exception_throw + 44 
    2 CoreFoundation      0x004596f5 -[NSObject(NSObject) doesNotRecognizeSelector:] + 277 
    3 CoreFoundation      0x003a4857 ___forwarding___ + 1047 
    4 CoreFoundation      0x003a441e _CF_forwarding_prep_0 + 14 
    5 UIKit        0x00f149aa -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 2767 
    6 UIKit        0x00f18ebc -[UITableViewRowData numberOfRows] + 98 
    7 UIKit        0x00d57bb0 -[UITableView noteNumberOfRowsChanged] + 133 
    8 UIKit        0x00d57442 -[UITableView reloadData] + 1055 
    9 UIKit        0x00d5b54d -[UITableView _reloadDataIfNeeded] + 78 
    10 UIKit        0x00d60ed5 -[UITableView layoutSubviews] + 36 
    11 UIKit        0x00cd9223 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 601 
    12 libobjc.A.dylib      0x01db5763 -[NSObject performSelector:withObject:] + 70 
    13 QuartzCore       0x04441b87 -[CALayer layoutSublayers] + 152 
    14 QuartzCore       0x044359e9 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 397 
    15 QuartzCore       0x04441ace -[CALayer layoutIfNeeded] + 160 
    16 UIKit        0x00db72e3 -[UIViewController window:setupWithInterfaceOrientation:] + 309 
    17 UIKit        0x00ca5a80 -[UIWindow _rotateToBounds:withAnimator:transitionContext:] + 667 
    18 UIKit        0x00ca8388 -[UIWindow _rotateWindowToOrientation:updateStatusBar:duration:skipCallbacks:] + 2151 
    19 UIKit        0x00caa074 -[UIWindow _setRotatableClient:toOrientation:applyTransformToWindow:updateStatusBar:duration:force:isRotating:] + 6723 
    20 UIKit        0x00ca785d -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:] + 128 
    21 UIKit        0x00ca77d6 -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:] + 84 
    22 UIKit        0x00ca769e -[UIWindow _setRotatableViewOrientation:updateStatusBar:duration:force:] + 115 
    23 UIKit        0x00ca7729 -[UIWindow _setRotatableViewOrientation:duration:force:] + 68 
    24 UIKit        0x00ca66b6 __57-[UIWindow _updateToInterfaceOrientation:duration:force:]_block_invoke + 120 
    25 UIKit        0x00ca6624 -[UIWindow _updateToInterfaceOrientation:duration:force:] + 406 
    26 UIKit        0x00ca7445 -[UIWindow setAutorotates:forceUpdateInterfaceOrientation:] + 905 
    27 UIKit        0x00cacb1f -[UIWindow setDelegate:] + 479 
    28 UIKit        0x00da4177 -[UIViewController _tryBecomeRootViewControllerInWindow:] + 184 
    29 UIKit        0x00c9f69a -[UIWindow addRootViewControllerViewIfPossible] + 683 
    30 UIKit        0x00c9f85c -[UIWindow _setHidden:forced:] + 313 
    31 UIKit        0x00c9fad9 -[UIWindow _orderFrontWithoutMakingKey] + 49 
    32 UIKit        0x00cae47b -[UIWindow makeKeyAndVisible] + 80 
    33 UIKit        0x00c4fa50 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3228 
    34 UIKit        0x00c528a3 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1507 
    35 UIKit        0x00c6c335 __84-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:]_block_invoke + 59 
    36 UIKit        0x00c515e3 -[UIApplication workspaceDidEndTransaction:] + 29 
    37 FrontBoardServices     0x033f42af -[FBSWorkspace clientEndTransaction:] + 87 
    38 FrontBoardServices     0x033fb71d __53-[FBSWorkspaceClient _queue_handleTransactionBookEnd]_block_invoke + 49 
    39 CoreFoundation      0x003772f0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 16 
    40 CoreFoundation      0x0036ba83 __CFRunLoopDoBlocks + 195 
    41 CoreFoundation      0x0036b1e8 __CFRunLoopRun + 936 
    42 CoreFoundation      0x0036ab7b CFRunLoopRunSpecific + 443 
    43 CoreFoundation      0x0036a9ab CFRunLoopRunInMode + 123 
    44 UIKit        0x00c50efa -[UIApplication _run] + 571 
    45 UIKit        0x00c54dee UIApplicationMain + 3727 
    46 firstapp       0x00005011 top_level_code + 97 
    47 firstapp       0x0000504b main + 43 
    48 libdyld.dylib      0x022beac5 start + 1 
    49 ???         0x00000001 0x0 + 1 
) 
libc++abi.dylib: terminating with uncaught exception of type NSException 
(lldb) 

Я попытался следующие трассировки стека к методу предположительно вызывает проблему, но может» t найти что-нибудь необычное (в настоящее время после учебника). Я также включил мой ViewController.swift:

import UIKit 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

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

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { 
     return 10 
    } 


    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { 
     let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell") 

     cell.text = "Row #\(indexPath.row)" 
     cell.detailTextLabel.text = "Subtitle #\(indexPath.row)" 

     return cell 
    } 

} 

EDIT: В том числе источник для Main.storyboard:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="6154.17" systemVersion="13D65" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="CLE-J8-Gwc"> 
    <dependencies> 
     <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6153.11"/> 
    </dependencies> 
    <scenes> 
     <!--View Controller--> 
     <scene sceneID="53f-Xy-Vbi"> 
      <objects> 
       <viewController id="CLE-J8-Gwc" sceneMemberID="viewController"> 
        <view key="view" contentMode="scaleToFill" id="uoO-21-5Iu"> 
         <rect key="frame" x="0.0" y="0.0" width="320" height="568"/> 
         <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> 
         <subviews> 
          <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" id="Kl0-es-OXb"> 
           <rect key="frame" x="0.0" y="0.0" width="320" height="568"/> 
           <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> 
           <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> 
           <connections> 
            <outlet property="dataSource" destination="CLE-J8-Gwc" id="HG5-Ye-UOQ"/> 
            <outlet property="delegate" destination="CLE-J8-Gwc" id="I76-0E-fPy"/> 
           </connections> 
          </tableView> 
         </subviews> 
         <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> 
        </view> 
       </viewController> 
       <placeholder placeholderIdentifier="IBFirstResponder" id="yaa-zI-5Eu" userLabel="First Responder" sceneMemberID="firstResponder"/> 
      </objects> 
      <point key="canvasLocation" x="110.66666666666666" y="562.08333333333337"/> 
     </scene> 
    </scenes> 
    <simulatedMetricsContainer key="defaultSimulatedMetrics"> 
     <simulatedStatusBarMetrics key="statusBar"/> 
     <simulatedOrientationMetrics key="orientation"/> 
     <simulatedScreenMetrics key="destination" type="retina4"/> 
    </simulatedMetricsContainer> </document> 

Я проверил тонны вопросов относительно ту же ошибку и не может показаться найти что-нибудь быстрое или конкретное, что решает мою текущую проблему.

Спасибо!

+0

Я хотел бы добавить, что иногда нет ошибок. Это была ошибка Xcode. Все, что вам нужно сделать, это Clean & Run! –

ответ

23

Как указано в первой строке вашего дампа, вы пытаетесь отправить ...numberOfRows... объекту класса UIViewController, но этот метод реализуется только в вашем подклассе.

В вашем файле nib вам необходимо изменить класс вашего контроллера вида от UIViewController (по умолчанию) до ViewController.

Откройте раскадровку (или файл NIB) выбрать сам контроллер (он имеет значок в нижней части (или вершины в Xcode 6), что будет говорить «View Controller», когда вы мыши над ним.

enter image description here

Затем выберите 3-ю иконку из панели свойств и на вершине, где он говорит: «Пользовательский класс» введите «ViewController»

enter image description here

+0

Извините, я чрезвычайно новичок в развитии iOS, как я могу это сделать? Я попытался найти исходный код для моего файла .storyboard, и я не вижу ссылок на UIViewController. Я включу источник в вопрос как редактирование, а также – pgoggijr

+0

Вообще говоря, не беспокойтесь, отправляя xml для раскадровки, на самом деле он не предназначен для чтения человеком, независимо от того, что говорят xml-philes. –

+0

Это сработало! спасибо за помощь и разъяснение – pgoggijr

2

Оказывается, что источник данных вашей таблицы не установлен в класс ViewController:

-[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0xb20fcf0 

Дважды проверьте, чтобы убедиться, что вы настроили свой XIB файл/раскадровку правильно.

+0

источник данных в настоящее время выглядит так: [Imgur] (http://i.imgur.com/lTVfNi2.png) – pgoggijr

0

Изменить код:

override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { 

    // Return the number of rows in the section. 
    return 10 
} 
+0

Пробовал это, без изменений – pgoggijr

Смежные вопросы