Using makeObjectsPerformSelector: withObject: with false boolean

I have an array of UITextField objects called _fields . I want to be able to immediately tell them everything, to set them as highlighted , and then do the same to turn this highlighted property into NO . This piece of code works.

 [fields makeObjectsPerformSelector:@selector(setHighlighted:) withObject:@YES]; 

This part, however, does not work; I can’t get him to do anything.

 [fields makeObjectsPerformSelector:@selector(setHighlighted:) withObject:@NO]; 

It really works.

 for (UITextField *field in fields) { field.highlighted = NO; } 

What gives? I would love to use the message makeObjectsPerformSelector:withObject: but I don't really like using @NO . Can someone explain this behavior to me or say that I am doing something wrong?

+4
source share
3 answers

The setHighlighted: method accepts a BOOL type. This is not an object type. Therefore, you cannot use the makeObjectsPerformSelector:withObject: method.

It seems to work when passing @YES , because you are passing a pointer to an object in the BOOL parameter. A nonzero value is treated as a YES value. When you pass @NO , you also pass a pointer. Since this is also a nonzero value, it is also treated as a YES value.

You can get the desired NO effect by passing nil the withObject: parameter. The nil value will be 0, which is the same value as NO .

But these are kludges. Use a loop approach instead.

+12
source

Rmaddy's answer explains why using makeObjectsPerformSelector:withObject: will not work.

You can do this most briefly using KVC:

 [fields setValue:@NO forKey:@"hidden"]; 

This works because NSArray passes the message setValue:forKey: each of its elements, and KVC correctly expands the value in the box when the property type is primitive.

+13
source

You should try using blocks because setHighlighted accepts BOOL as a parameter, not a pointer (NSNumber *):

 [fields enumerateObjectsUsingBlock:^(UITextField *obj, NSUInteger idx, BOOL *stop) { obj.highlighted = YES; // or NO }]; 
0
source

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


All Articles