Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Using makeObjectsPerformSelector:withObject: with a false boolean

I've got an array of UITextField objects called _fields. I want to be able to message them all at once to set them to be highlighted, and then do the same to turn that highlighted property to NO. This part of the code works.

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

This part, however, does not; I can't get it to do anything.

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

This does work, however.

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

What gives? I would've liked to have used the makeObjectsPerformSelector:withObject: message, but I'm not getting much love with @NO. Can someone explain this behavior to me, or tell me if I'm doing something wrong?

like image 562
Ben Kreeger Avatar asked Nov 29 '22 02:11

Ben Kreeger

2 Answers

rmaddy's answer explains why using makeObjectsPerformSelector:withObject: won't work.

You can do this most succinctly by using KVC:

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

This works because NSArray passes the setValue:forKey: message through to each of its elements, and KVC properly unwraps the boxed value when the property's type is primitive.

like image 151
rob mayoff Avatar answered Dec 10 '22 23:12

rob mayoff

The setHighlighted: method takes a type of BOOL. This is not an object type. Therefore you can't use the makeObjectsPerformSelector:withObject: method.

It seems to work when passing @YES because you are passing a pointer to an object to the BOOL parameter. The non-zero value gets treated like a YES value. When you pass @NO you are also passing a pointer. Since it is also a non-zero value, it also gets treated like a YES value.

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

But these are kludges. Use the loop approach instead.

like image 23
rmaddy Avatar answered Dec 10 '22 23:12