How can I pass an NSNumber to a method waiting for a bool?

[[self.view.window subviews] makeObjectsPerformSelector:@selector(setUserInteractionEnabled:) withObject:[NSNumber numberWithBool:NO]]; 

I saw this code in an answer to another question ( How to disable touch input to all views except the top view? ), And it surprised me when it worked, since setUserInteractionEnabled: expects BOOL (which as an objective-c object cannot be passed in methods like performSelector:withObject: .

Where is the documentation that says the NSNumber transfer is ok? Does it work for all methods or do I need a special implementation? And it only works with BOOL, or can it be done using types like int ?

+6
source share
3 answers

If you just want your code to work, upgrade and accept Paul.s.'s answer. If you want to read about nerds doing experiments, go ahead. In the comments on my initial answer, there were some interesting discussions that I summarized below.

This does not work. I tried this in an iOS project, the userInteractionEnabled property is not affected by sending performSelector:withObject: This is consistent with the documentation for NSObject, which states:

aSelector must identify a method that takes a single argument of a type identifier. For methods with other argument types and return values, use NSInvocation.

Currently, the legendary Peter Hosey has built a sample creation tool here that looks bizzarely working enough when you pass it a double as well as a float, as I recognized myself.

To add curiosity to curiosity, this does not work in an iOS project (double or float).

In general, I think we can say the following:

  • If it ever works, it works randomly and should not rely on
  • An accepted or confirmed response to a stack overflow is not always correct.
+3
source

You cannot pass NSNumber as an object and output it as BOOL on the other end. However, there are some workarounds.

  • Use NSInvocation. You will need to create an NSArray category that uses NSInvocation. This is a little dirty.

  • Create a UIView category using the setUserInteractionEnabled: -like function (with the same name?), Which works with NSNumber, which then calls setUserInteractionEnabled: with a BOOL value for NSNumber. Sort of:

     @implementation UIView (Additions) - (BOOL)setUserInteractionEnabled2:(NSNumber *)aBool { self.userInteractionEnabled = [aBool boolValue]; } @end 
+2
source

I think you have already come to the conclusion that this will not work.

@senojsitruc offers several different ways to do this, but ignores the easiest solution.

 [self.view.window.subviews setValue:[NSNumber numberWithBool:NO] forKey:@"userInteractionEnabled"]; 

Documents for NSArray state:

SetValue: forKey:

Calls setValue: forKey: for each element of the array using the specified value and key.

+2
source

Source: https://habr.com/ru/post/904853/


All Articles