Cast of a non-Objective-C pointer type 'const UInt8 *' (aka 'const unsigned char *') to 'NSData *' is disallowed with ARC

StackOverflow https://stackoverflow.com/questions/22396504

  •  14-06-2023
  •  | 
  •  

Question

ok I'm completely new to Obj-C and iOS. I'm just trying out a DataLogging example for the Pebble watch on iOS and changing a few things to log the accelerometer reading.

I have this function:

- (BOOL)dataLoggingService:(PBDataLoggingService *)service hasByteArrays:(const UInt8 *const)data numberOfItems:(UInt16)numberOfItems forDataLoggingSession:(PBDataLoggingSessionMetadata *)sessionMetadata{

    //NSString *log = [NSString stringWithFormat:@"%s", data]; <-- this line compiles but display garbage on the view. So I try to use the line below.

    NSString *log = [[NSString alloc] initWithData:(NSData *)data encoding:NSASCIIStringEncoding]; <-- this line gave build error as in the post title

    [self addLogLine:log];

    // We consumed the data, let the data logging service know:
    return YES;
}

So any help would be greatly appreciated. Thanks.

Was it helpful?

Solution

First your error: it is telling you that cannot take a pointer to something which isn't an Objective-C object - you have a pointer to UInt8 - simply cast it to a pointer to an Objective-C object - NSData in your case as ARC (the Objective-C memory collector) doesn't know how to treat the result. You address this, if possible, with a bridge cast which tells ARC how to handle it. However in your case its not possible as you can't just cast an UInt8 * to an NSData * - the two refer to totally different things.

At a guess your method is passed a pointer to a sequence of bytes (hasByteArrays:) and the number of bytes in the sequence (numberOfItems), if that is correct then the method you are after is initWithBytes:length:encoding:, this method directly takes a pointer to a byte sequence. E.g.:

NSString *log = [[NSString alloc] initWithBytes:data
                                         length:numberOfItems
                                       encoding:NSASCIIStringEncoding];

OTHER TIPS

Try with below approach:

- (BOOL)dataLoggingService:(PBDataLoggingService *)service hasByteArrays:(const UInt8 *const)data numberOfItems:(UInt16)numberOfItems forDataLoggingSession:(PBDataLoggingSessionMetadata *)sessionMetadata{

     NSString *log = [NSString stringWithCString:(const char *)data encoding:NSUTF8StringEncoding];

    [self addLogLine:log];

    // We consumed the data, let the data logging service know:
    return YES;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top