Gup3rSuR4c
Gup3rSuR4c

Reputation: 9480

How to assign a value to a BOOL pointer in Objective-C?

I'm having a bit of a confusion on how to assign a value to a BOOL pointer? Here's my code:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    self.latitude.text = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
    self.longitude.text = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];

    if (!initialBroadcast) {
        initialBroadcast = YES; // Where I'm having troubles

        [broadcastTimer fire];
    };
}

The compiler keeps telling me this: Incompatible integer to pointer conversion assigning to 'BOOL *' (aka 'signed char *') from 'BOOL' (aka 'signed char').

I'd appreciate a clarification on this since I am a nubski.


UPDATE

As many of you have pointed out, I am apparently abusing the declaration of a BOOL by using a pointer for it. To be honest, I don't know why I used it, but since I'm new to Objective-C it must have worked for what I was doing so it stuck.

Anyway, I have since changed the declaration to:

//  In .h
@interface ... {
    BOOL initialBroadcast;
}

@property BOOL initialBroadcast;

//  In .m
@synthesize initialBroadcast;

So, am I on the right track now?

Upvotes: 37

Views: 62722

Answers (4)

bbum
bbum

Reputation: 162712

The problem isn't the assignment, it is much more likely that you declared your instance variable to be BOOL *initialBroadcast;.

There is no reason to declare the instance variable to be a pointer (at least not unless you really do need a C array of BOOLs).. Remove the * from the declaration.

As well, that will fix your currently incorrect if() test. As it is, it is checking to see if the pointer is set, not the value.

Upvotes: 59

DavidMFrey
DavidMFrey

Reputation: 1668

You need to say

*initialBroadcast = YES;

initialBroadcast is a pointer aka memory address. The * gives access to the value at the memory address that the pointer holds. So initialBroadcast is a memory address, but *initialBroadcast is a boolean or char.

Upvotes: 60

Mahesh
Mahesh

Reputation: 34615

Change -

initialBroadcast = YES;

to

(*initialBroadcast) = YES;

Since, you are assigning value to the location the pointer points to( assuming it is initialized ), initialBroadCast should be dereferenced first.

Upvotes: 10

epatel
epatel

Reputation: 46051

Could be that you should write

*initialBroadcast = YES; // Where I'm having troubles

The line before seem to be a standard check to see that the pointer is valid (not nil)

Upvotes: 3

Related Questions