0

Why can I declare/define a method like this:

@interface Dog : NSObject

- (void) doStuff:(NSInteger)val;

@end

...

@implementation Dog

- (void) doStuff:(NSInteger)val {

    NSLog(@"arg was valid");

}

@end

...and call it like this:

Dog* mydog = [[Dog alloc] init];
[mydog doStuff:YES];  //=>arg was valid

I've read that BOOL is a typedef for a signed char. Usually in Xcode6, if the types don't exactly match, I get all kinds of warnings that tell me to cast to the proper type, and Xcode will insert the casts for me if I click on the right spot.

7stud
  • 46,922
  • 14
  • 101
  • 127
  • Ahh. *On 64-bit architectures, NSInteger and NSUInteger are defined as long and unsigned long, respectively.* So the cast from signed char to long happens automatically? – 7stud May 13 '15 at 20:07
  • Yup, no warning here: `signed char x = 104; NSLog(@"%c", x); //=>h long y = x; NSLog(@"%ld", y); //=>104` And no warnings going the other way: `long y = 258; NSLog(@"%ld", y); //=>258 signed char x = y; NSLog(@"%d", x); //=>2` – 7stud May 13 '15 at 20:21

1 Answers1

1

In the C family of languages - (Objective-)C(++) - the various boolean types (BOOL, bool, _Bool) are all classed as integer types. (char is also an integer type.)

Using a smaller integer type where a larger integer type is required is an implicit conversion, no cast is required.

Combine those and you can pass a BOOL as an NSInteger.

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86
  • I made two mistakes: 1)I though NSInteger was an object 2) I could not remember from my C++ days that a char was an integer type. However, your answer leaves my wondering why the example in my comment(under my answer) does not require a cast when converting a long to a char. – 7stud May 14 '15 at 00:22
  • @7stud - I was being kind to C. Storing into a smaller unsigned type is defined to truncate, storing into a smaller signed type is implementation defined. C is barely a typed language. – CRD May 14 '15 at 01:24