Objective-C에서 "인식 할 수없는 선택기가 인스턴스로 전송되었습니다"오류
버튼을 만들고 해당 작업을 추가했지만 호출하자마자이 오류가 발생했습니다.
-[NSCFDictionary numberButtonClick:]: unrecognized selector sent to instance
0x3d03ac0 2010-03-16 22:23:58.811
Money[8056:207] *** Terminating app
due to uncaught exception
'NSInvalidArgumentException', reason:'*** -[NSCFDictionary numberButtonClick:]: unrecognized selector sent to instance 0x3d03ac0'
이것은 내 코드입니다.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
UIButton *numberButton = [UIButton buttonWithType:UIButtonTypeCustom];
numberButton.frame = CGRectMake(10, 435, 46, 38);
[numberButton setImage:[UIImage imageNamed:@"one.png"] forState:UIControlStateNormal];
[numberButton addTarget:self action:@selector(numberButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: numberButton];
}
return self;
}
-(IBAction)numberButtonClick:(id)sender{
NSLog(@"---");
}
뷰 컨트롤러를 올바르게 관리하는 메모리가 아니며 어느 시점에서 할당이 해제되는 것처럼 보입니다. 이는 numberButtonClicked:
뷰 컨트롤러가 이전에 차지했던 메모리를 차지하는 다른 객체로 메소드가 전송되도록합니다 ...
뷰 컨트롤러를 올바르게 유지 / 해제해야합니다.
내가했던 것처럼 Google을 통해 여기에 오는 사람들에게는 아마도 ARC의 Xcode 4.2 + / iOS 5 이상에 더 관련이 있습니다. " 인식 할 수없는 선택기가 인스턴스로 전송되었습니다 "와 동일한 오류가 발생했습니다 . 필자의 경우 UIButton의 대상 작업을 발신자 매개 변수로 전달하도록 설정했지만 나중에 필요하지 않고 코드에서 제거했습니다. 따라서 다음과 같은 것이 있습니다.
- (IBAction)buttonPressed:(UIButton *)sender {
로 변경되었습니다 :
- (IBAction)buttonPressed {
문제의 UIButton을 마우스 오른쪽 버튼으로 클릭하면 Touch Up Inside 이벤트가 뷰 컨트롤러 buttonPressed : 메서드와 관련이 있음을 보여주었습니다. 이것을 제거하고 수정 된 메소드에 다시 할당하면 대우를했습니다.
이것은이 문제에 대한 Google의 최고 답변이지만 다른 원인 / 결과가있었습니다. 다른 사람들 이이 문제를 우연히 발견 할 경우 2 센트를 더할 것이라고 생각했습니다.
오늘 아침에 비슷한 문제가 발생했습니다. 문제를 제공하는 UI 항목을 마우스 오른쪽 버튼으로 클릭하면 어떤 연결이 생성되었는지 확인할 수 있습니다. 제 경우에는 두 가지 동작으로 연결된 버튼이 있습니다. 마우스 오른쪽 버튼 클릭 메뉴에서 작업을 삭제하고 다시 연결하여 문제를 해결했습니다.
따라서 작업이 올바르게 연결되어 있는지 확인하십시오.
좋아, 나는 여기에 칩을 넣어야한다. OP 는 버튼을 동적으로 만들었습니다 . 나는 비슷한 문제를 겪었고 대답 (헌팅 시간 후)이 너무 단순하여 나를 아프게했습니다.
사용할 때:
action:@selector(xxxButtonClick:)
or (as in my case)
action:NSSelectorFromString([[NSString alloc] initWithFormat:@"%@BtnTui:", name.lowercaseString])
문자열 끝에 콜론을 넣으면 발신자가 전달됩니다. 문자열의 끝에 콜론을 배치하지 않으면 콜론이 발생하지 않으며 수신자는 콜론을 예상 할 경우 오류가 발생합니다. 이벤트 이름을 동적으로 작성하는 경우 콜론을 놓치기 쉽습니다.
수신자 코드 옵션은 다음과 같습니다.
- (void)doneBtnTui:(id)sender {
NSLog(@"Done Button - with sender");
}
or
- (void)doneBtnTui {
NSLog(@"Done Button - no sender");
}
평소와 같이 항상 놓치는 것은 분명한 대답입니다.
필자의 경우 함수는 인수를 기대하지 않았지만 버튼은 오류를 발생시키는 버튼을 보내도록 구성되었습니다. 이 문제를 해결하려면 이벤트 처리기를 다시 연결해야했습니다.
내 기능은 다음과 같습니다.
인수가 포함되어 있지 않습니다.
내 버튼 구성 이미지는 다음과 같습니다 (버튼을 마우스 오른쪽 버튼으로 클릭하면 볼 수 있음).
3 개의 이벤트 핸들러가 있습니다.
이 문제를 해결하려면 각 이벤트 항목 중 하나가 enterPressed 함수에 대한 참조를 전송했기 때문에 각 이벤트 항목을 제거해야했습니다. 이러한 항목을 제거하려면 항목이 표시되지 않을 때까지 각 항목 이름 옆에있는 작은 x 아이콘을 클릭했습니다.
다음으로 버튼을 이벤트에 다시 연결해야했습니다. 이렇게하려면 Control 키를 누른 상태에서 단추에서 동작으로 선을 드래그하십시오. "연결 작업"이라고 표시되어야합니다. 참고 : 어떤 이유로 든 XCode를 다시 시작해야했습니다. 그렇지 않으면 함수 위 또는 아래에 액션 (일명 새 액션 만들기)을 삽입 할 수 있습니다.
이제 인수가없는 버튼 이벤트에 연결된 단일 이벤트 핸들러가 있어야합니다.
이 답변은 @Leonard Challis의 답변을 칭찬합니다.
인터페이스 빌더에서보기의 "클래스"를 설정하지 않은 경우에도 발생할 수 있습니다.
필자의 경우 NSNotificationCenter를 사용하고 인수는 없지만 콜론을 추가하는 선택기를 사용하려고했습니다. 콜론을 제거하면 문제가 해결되었습니다.
When using a selector name, don't use a trailing colon if there are no arguments. If there's one argument, use one trailing colon. If there are more than one argument, you must name them along with a trailing colon for each argument.
See Adam Rosenfield's answer here: Selectors in Objective-C?
I had this problem with a Swift project where I'm creating the buttons dynamically. Problem code:
var trashBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "newButtonClicked")
}
func newButtonClicked(barButtonItem: UIBarButtonItem) {
NSLog("A bar button item on the default toolbar was clicked: \(barButtonItem).")
}
The solution was to add a full colon ':' after the action: e.g.
var trashBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "newButtonClicked:")
}
func newButtonClicked(barButtonItem: UIBarButtonItem) {
NSLog("A bar button item on the default toolbar was clicked: \(barButtonItem).")
}
Full example here: https://developer.apple.com/library/content/samplecode/UICatalog/Listings/Swift_UIKitCatalog_DefaultToolbarViewController_swift.html
The most obvious cause of this (included for completeness) is improperly casting a pointer and calling a method of the wrong class.
NSArray* array = [[NSArray alloc] init];
[(NSDictionary*)array objectForKey: key]; // array is not a dictionary, hence exception
I had a similar problem, but for me the solution was slightly different. In my case, I used a Category to extend an existing class (UIImage for some resizing capabilities - see this howto in case you're interested) and forgot to add the *.m file to the build target. Stupid error, but not always obvious when it happens where to look. I thought it's worth sharing...
I also had the same issue.
I deleted my uibutton in my storyboard and recreated it .. now everything works fine.
This happened to my because accidentally erase the " @IBAction func... " inside my UIViewcontroller class code, so in the Storyboard was created the Reference Outlet, but at runtime there was any function to process it.
The solution was to delete the Outlet reference inside the property inspector and then recreate it dragging with command key to the class code.
Hope it helps!
I think you should use the void, instead of the IBAction in return type. because you defined a button programmatically.
I had the same error and I discovered the following:
When you use the code
[self.refreshControl addTarget:self action:@selector(yourRefreshMethod:) forControlEvents:UIControlEventValueChanged];
You may think it's looking for the selector:
- (void)yourRefreshMethod{
(your code here)
}
But it's actually looking for the selector:
- (void)yourRefreshMethod:(id)sender{
(your code here)
}
That selector doesn't exist, so you get the crash.
You can change the selector to receive (id)sender in order to solve the error.
But what if you have other functions that call the refresh function without providing a sender? You need one function that works for both. Easy solution is to add another function:
- (void)yourRefreshMethodWithSender:(id)sender{
[self yourRefreshMethod];
}
And then modify the refresh pulldown code to call that selector instead:
[self.refreshControl addTarget:self action:@selector(yourRefreshMethodWithSender:) forControlEvents:UIControlEventValueChanged];
I'm also doing the Stanford iOS course on an older Mac that can't be upgraded to the newest version of Mac OSX. So I'm still building for iOS 6.1, and this solved the problem for me.
Another possible solution: Add '-ObjC' to your linker arguments.
Full explanation is here: Objective-C categories in static library
I think the gist is: if the category is defined in a library you are statically linking with, the linker isn't smart enough to link in category methods. The flag above makes the linker link in all objective C classes and categories, not just ones it thinks it needs to based on analyzing your source. (Please feel free to tune or correct that answer. I'm knew to linked languages, so I'm just parroting here).
I'm currently learning iOS development and going through the "Beginning iOS6 Development" book by aPress. I was getting the same error in Chapter 10:Storyboards.
It took me two days to figure it out but found out I accidentally set the TableView cell's tag to 1 when I shouldn't have. For anyone else doing this book and receive a similar error I hope this helps.
I really hope future errors in my code are easier to find! hahaha. The debug error did nothing to push me in the right direction to figuring it out (or at least I'm too new to understand the debugger, lol).
In my case I was using a UIWebView and I passed a NSString in the second parameter instead of a NSURL. So I suspect that wrong class types passed to a functions can cause this error.
..And now mine
I had the button linked to a method which accessed another button's parameter and that worked great BUT as soon I tried to do something with the button itself, I got a crash. While compiling, no error has been displayed.. Solution?
I failed to link the button to the file's owner. So if anyone here is as stupid as me, try this :)
Yet another slightly different solution/case.
I am using Xamarin and MvvmCross and I was trying to bind the UIButton to a ViewModel. I had the UIButton wired up to an Outlet and a TouchUpInside.
When Binding I only use the Outlet:
set.Bind (somethingOutlet).For ("TouchUpInside").To(vm => vm.Something);
All I had to do was remove the action (TouchUpInside) connection in XCode and that solved it.
P.S. I guess this is in its base all related to the previous answers and to @Chris Kaminski in particular, but I hope this helps someone...
Cheers.
I had the same issue. The problem for me was that one button had two Action methods. What I did was create a first action method for my button and then deleted it in the view controller, but forgot to disconnect the connection in the main storyboard in the connection inspector. So when I added a second action method, there were now two action methods for one button, which caused the error.
For me, it was a leftover connection created in interfacebuilder bij ctrl-dragging. The name of the broken connection was in the error-log
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[NameOfYourApp.NameOfYourClass nameOfCorruptConnection:]:
unrecognized selector sent to instance 0x7f97a48bb000'
I had an action linked to a button. Pressing the button crashed the app because the Outlet no longer existed in my code. Searching for the name in the log led me to it in the storyboard. Deleted it, and the crash was gone!
On my case I solved the problem after 2 hours :
The sender (a tabBar item) wasn't having any Referencing Outlet. So it was pointing nowhere.
Juste create a referencing outlet corresponding to your function.
Hope this could help you guys.
I'm replying to Leonard Challis, since I was also taking the Stanford iOS class C193P, as was user "oli206"
"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:"
The problem was that I had the "Enter" button on the calculator connected twice,and a friend pointed out that doing an inspection of the button in the Storyboard showed that 2 entries were on the "Touch Up Inside" attributes when I right clicked on the "Enter" button. Erasing one of the two "Touch Up Inside" "Sent Events" solved the problem.
This showed that the problem is triggered (for the C193P video class on the Calculator Walkthrough on Assignment 1) as 2 sent events, one of which was causing the exception.
It can happen when you do not assign the ViewController to the ViewControllerScene in the InterfaceBuilder. So the ViewController.m is not connected to any scene.
Including my share. I got stuck on this for a while, until I realized I've created a project with ARC(Automatic counting reference) disabled. A quick set to YES on that option solved my issue.
Another really silly cause of this is having the selector defined in the interface(.h) but not in the implementation(.m) (p.e. typo)
Another reason/solution to add to the list. This one is caused by iOS6.0 (and/or bad programming). In older versions the selector would match if the parameter types matched, but in iOS 6.0 I got crashes in previously working code where the name of the parameter wasn't correct.
I was doing something like
[objectName methodName:@"somestring" lat:latValue lng:lngValue];
but in the definition (both .h and .m) I had
(viod) methodName:(NSString *) latitude:(double)latitude longitude:(double)longitude;
This worked fine on iOS5 but not on 6, even the exact same build deployed to different devices.
I don't get why the compiler coudn't tell me this, anyway - problem soled.
This also might happen when you want to set a property from a ControllerA to a public property inside a custom ControllerB class and you haven't set the "Custom Class" inside the identity inspector in storyboards yet.
My problem and solution was different and I thought I should post it here so that future readers can save their head from banging to the wall.
I was allocating different xib to same UIVIewController and even after searching everywhere I couldn't find how to correct it. Then I checked my AppDelegate where I was calling initWithNibName
and can see that while copying the code, I changed the xib name, but forgot to change UIViewController
class. So if none of the solution works for you, check your initWithNibName
method.
제약 조건 인수가 충돌하여 나에게 일어났습니다.
'Programing' 카테고리의 다른 글
문자열에서 모든 선행 0을 제거하는 방법 (0) | 2020.06.12 |
---|---|
__MACOSX 폴더없이 Mac zip 압축? (0) | 2020.06.12 |
"다른 사용자가이 기기에 호환되지 않는 버전을 이미 설치했기 때문에이 앱을 설치할 수 없습니다" (0) | 2020.06.12 |
값에 관계없이 유형이 항상 특정 크기 인 이유는 무엇입니까? (0) | 2020.06.12 |
컨트롤러에서 양식에 액세스 할 수 있습니까? (0) | 2020.06.12 |