Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass boolean value by reference

Is is possible in objective c to pass a boolean value by reference? I have a number of boolean properties that I need to manage, so I'd like to encapsulate the toggling of these values into a single function that I can call from each button click event. Here is one example:

@interface MyViewController()
@property (nonatomic) BOOL *sendEmails;
@end

Then in a UIButton click event, I have this method call:

[self updateEmailPreference:self.sendEmails button:self.noEmailsCheckBox];

Which calls this method:

- (void) updateEmailPreference : (BOOL *) b
                        button : (UIButton *) button
{
    if (*b) {*b = NO;}
    else {*b = YES;}

    if (*b) {
        [button setBackgroundImage:[UIImage imageNamed:@"checked_checkbox"] forState:UIControlStateNormal];
    } else {
        [button setBackgroundImage:[UIImage imageNamed:@"unchecked_checkbox"] forState:UIControlStateNormal];
    }
}

But unfortunately, this crashes on the if (*b)... block. Is this possible? Thanks!

like image 235
AndroidDev Avatar asked Oct 20 '22 17:10

AndroidDev


1 Answers

Probably better to do:

@interface MyViewController()
@property (nonatomic) BOOL sendEmails;
@end

For the method call:

[self updateEmailPreference:&(self ->_sendEmails) button:self.noEmailsCheckBox];

With the method still:

- (void) updateEmailPreference : (BOOL *) b
                        button : (UIButton *) button
{
    if (*b) {*b = NO;}
    else {*b = YES;}

    if (*b) {
        [button setBackgroundImage:[UIImage imageNamed:@"checked_checkbox"] forState:UIControlStateNormal];
    } else {
        [button setBackgroundImage:[UIImage imageNamed:@"unchecked_checkbox"] forState:UIControlStateNormal];
    }
}

(Do note that there can be confusion about the variable to use in the call statement. If it's a property you must use the ivar reference and not the dot-qualified property, and the ivar name must have the _ prefix or not depending on how your properties are declared. Or just use a local variable, and copy the property value into and out of that as required.)

like image 172
Hot Licks Avatar answered Nov 03 '22 02:11

Hot Licks