Search code examples
objective-cnslognsrange

NSRange output of location and length


An issue I have (maybe it is really easy to solve, but I am new to Obj-C. I want to print out the location and length of NSRange I created, but I get an error message. Here the code

NSRange tmpRange = [newData rangeOfData:segmentToFind options:kNilOptions range:NSMakeRange(0u, [newData length])];

NSLog(@"%@ - range location : %lu", [tmpRange location];

The error message I get is:

Bad receiver type 'NSRange' (aka 'struct _NSRange')

Solution

  • NSRange starts with the letters NS, but it isn't an NSObject. It is an ordinary struct, like a struct in C or in C++. So to access location and length, you just use range.location and range.length. There are other structs like that, like NSRect, NSPoint, NSSize.

    You noticed already what the compiler said: NSRange is a typedef for the type "struct _NSRange { ... }".

    And then there are types like NSInteger and NSUInteger which also start with NS but which are really just primitive types (int or long, unsigned int or unsigned long).