인프런 커뮤니티 질문&답변

박호정님의 프로필 이미지

작성한 질문수

성공적인 진짜 iOS 개발자 되기 [기초부터 실무까지]

네트워크 처리 1

에러 질문 [UITextField setDataSource:]: unrecognized selector sent to instance 0x107079600"

24.09.25 13:01 작성

·

30

0

강의 수강 중 35분 정도까지 따라한 뒤 실행했는데, 다음 에러가 발생했는데 이유를 잘 모르겠습니다.

다음처럼 에러가 발생하였는데요. 에러 내용과 작성한 코드들 첨부드립니다.

image.png

 

 

Exception	NSException *	"-[UITextField setDataSource:]: unrecognized selector sent to instance 0x107079600"	0x0000600000c9d170

에러 전체 내용


*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITextField setDataSource:]: unrecognized selector sent to instance 0x107079600'
*** First throw call stack:
(
	0   CoreFoundation                      0x00000001804b70ec __exceptionPreprocess + 172
	1   libobjc.A.dylib                     0x000000018008ede8 objc_exception_throw + 72
	2   CoreFoundation                      0x00000001804ccc54 +[NSObject(NSObject) instanceMethodSignatureForSelector:] + 0
	3   UIKitCore                           0x0000000185ace7a8 -[UIResponder doesNotRecognizeSelector:] + 232
	4   CoreFoundation                      0x00000001804bb3ec ___forwarding___ + 1268
	5   CoreFoundation                      0x00000001804bdb0c _CF_forwarding_prep_0 + 92
	6   CurrencyConverterApp.debug.dylib    0x000000010508d1ec $s20CurrencyConverterApp20PickerViewControllerC11viewDidLoadyyF + 648
	7   CurrencyConverterApp.debug.dylib    0x000000010508d270 $s20CurrencyConverterApp20PickerViewControllerC11viewDidLoadyyFTo + 36
	8   UIKitCore                           0x000000018533369c -[UIViewController _sendViewDidLoadWithAppearanceProxyObjectTaggingEnabled] + 80
	9   UIKitCore                           0x0000000185338238 -[UIViewController loadViewIfRequired] + 908
	10  UIKitCore                           0x000000018529db34 -[UINavigationController _ensureToViewControllersViewIsLoaded:] + 84
	11  UIKitCore                           0x000000018529df70 -[UINavigationController transitionConductor:willTransitionFromViewController:toViewController:] + 184
	12  UIKitCore                           0x0000000185c35c70 -[_UIViewControllerTransitionConductor startDeferredTransitionIfNeeded] + 452
	13  UIKitCore                           0x00000001852951a4 -[UINavigationController __viewWillLayoutSubviews] + 80
	14  UIKitCore                           0x000000018527cf58 -[UILayoutContainerView layoutSubviews] + 168
	15  UIKitCore                           0x000000018601c0c4 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2404
	16  QuartzCore                          0x000000018b06ceb0 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 432
	17  QuartzCore                          0x000000018b077c34 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 124
	18  QuartzCore                          0x000000018afacc58 _ZN2CA7Context18commit_transactionEPNS_11TransactionEdPd + 464
	19  QuartzCore                          0x000000018afdb468 _ZN2CA11Transaction6commitEv + 652
	20  UIKitCore                           0x0000000185abb7b4 __34-[UIApplication _firstCommitBlock]_block_invoke_2 + 32
	21  CoreFoundation                      0x000000018041b0ec __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20
	22  CoreFoundation                      0x000000018041a824 __CFRunLoopDoBlocks + 352
	23  CoreFoundation                      0x00000001804150c8 __CFRunLoopRun + 812
	24  CoreFoundation                      0x0000000180414960 CFRunLoopRunSpecific + 536
	25  GraphicsServices                    0x0000000190183b10 GSEventRunModal + 160
	26  UIKitCore                           0x0000000185aa2b40 -[UIApplication _run] + 796
	27  UIKitCore                           0x0000000185aa6d38 UIApplicationMain + 124
	28  UIKitCore                           0x0000000184e9a184 block_destroy_helper.22 + 9660
	29  CurrencyConverterApp.debug.dylib    0x000000010508820c $sSo21UIApplicationDelegateP5UIKitE4mainyyFZ + 120
	30  CurrencyConverterApp.debug.dylib    0x0000000105088184 $s20CurrencyConverterApp0C8DelegateC5$mainyyFZ + 44
	31  CurrencyConverterApp.debug.dylib    0x0000000105088288 __debug_main_executable_dylib_entry_point + 28
	32  dyld                                0x00000001050dd410 start_sim + 20
	33  ???                                 0x0000000104e1e274 0x0 + 4376879732
)
libc++abi: terminating due to uncaught exception of type NSException

 

AppDelegate.swift

//
//  AppDelegate.swift
//  CurrencyConverterApp
//
//  Created by hojeongpark on 9/24/24.
//

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }


}

 

PickerViewController.swift

//
//  ViewController.swift
//  CurrencyConverterApp
//
//  Created by hojeongpark on 9/24/24.
//

import UIKit

class PickerViewController: UIViewController {
    var rates: [(String, Double)]?
    
    @IBOutlet weak var currencyPicker: UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.navigationItem.title = "Currency List"
        
        currencyPicker.delegate = self
        currencyPicker.dataSource = self
        
        fetchJson()
    }

    
    func fetchJson() {
        let urlString = "https://open.er-api.com/v6/latest/USD"
        guard let url = URL(string: urlString) else {
            return
        }
        
        print("fetchJson")
        
        // data task
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else {
                return
            }
            
            do {
                let currencyModel = try JSONDecoder().decode(CurrencyModel.self, from: data)
                
                self.rates = currencyModel.rates?.sorted{ $0.key < $1.key }
                
                // 피커 새로고침 해야 데이터 내용이 보입니다.
                DispatchQueue.main.async {
                    self.currencyPicker.reloadAllComponents()
                }
                
                print("currencyModel", currencyModel)
            }catch{
                print("error", error)
            }
            
        }.resume()
    
    }
}


extension PickerViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return rates?.count ?? 0
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return rates?[row].0
    }
    
    
}

답변 2

0

iOS Developer - 이정님의 프로필 이미지
iOS Developer - 이정
지식공유자

2024. 09. 25. 13:07

안녕하세요

IBOutlet으로 연결할 때

PickerView를 TextField에 연결했다거나 하는등 잘못 연결된게 있는지 한번 확인이 필요해 보입니다.

 

박호정님의 프로필 이미지
박호정
질문자

2024. 09. 25. 13:44

다른 ui들은 다 제거하고 PickerView만 스토리보드에 만든 후 연결해보는 방식으로 하니 정상 동작하네요!

 

감사합니다.

0

인프런 AI 인턴님의 프로필 이미지

2024. 09. 25. 13:06

안녕하세요, 인프런 AI 인턴입니다.

박호정님, 질문을 주셔서 감사합니다. 보고 계신 에러 -[UITextField setDataSource:]: unrecognized selector sent to instance 0x107079600UITextField 객체에 존재하지 않는 메서드 setDataSource를 호출하려고 할 때 발생하는 문제입니다.

이 에러는 주로 UIPickerView와 관련된 설정에서 발생한 잘못된 연결 때문에 발생하는 경우가 많습니다. 특히, Interface Builder (스토리보드)에서 잘못된 연결이나 코드에서 잘못된 참조가 있는지 확인이 필요합니다.

아래는 몇 가지 해결책을 제시하는 링크입니다:

  • 오류가 나는 이유를 모르겠습니다:

    • 이 질문에서는 스토리보드에서 잘못된 클래스나 IBOutlet 연결로 인해 문제가 발생할 수 있으므로, 스토리보드 ID가 정확히 설정되어 있는지 확인하는 방법이 설명되어 있습니다.
  • 오류에 관해서 질문있습니다.:

    • 이 질문에서는 버튼과 함수 간의 연결 문제를 확인하는 방법에 대해 설명하고 있습니다. 동일하게, 스토리보드와 코드가 올바르게 연결되었는지 확인해 보세요.

따라서, 다음 단계를 따라 문제를 해결해 보세요:
1. 스토리보드 연결 확인: UIPickerView에 대해 올바르게 IBOutlet과 delegate 및 dataSource가 연결되어 있는지 확인합니다. 잘못된 연결이 있을 경우 제거하고 다시 연결해 보세요.
2. 코드의 delegate 및 dataSource 설정 확인:
- currencyPicker.delegate = self
- currencyPicker.dataSource = self
3. 다른 파일에서의 문제: 혹시 다른 파일에서 UITextField와 관련된 잘못된 설정이 있는지 확인해 보세요.

도움이 필요하시면 위의 링크를 참고하여 스토리보드와 코드 간의 연결 상태를 확인해 보는 것이 좋습니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.