Search code examples
iosobjective-ccore-bluetooth

Appending data to a string without losing previous data


I have this is on the top of my program:

@property (strong, nonatomic) NSMutableData         *data;

I thought this would allow me to store the value from every time this method runs:

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
{
    for (CBATTRequest *request in requests) {
        NSString *stringValue = [[NSString alloc] initWithData:   [request value] encoding:NSUTF8StringEncoding];



    // Have we got everything we need?
    if ([stringValue isEqualToString:@"EOM"]) {

        // We have, so show the data,
        [self.textview setText:[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]];


    }

    // Otherwise, just add the data on to what we already have
    [self.data appendData:[request value]];


}

}

This method waits for a write request to be received and stores the value in a string. I have a core bluetooth central that is sending three blocks of data. This is to get around the data transfer size restriction within bluetooth LE. The problem is I can't get the three values stored. I am trying to not just store the last value but add the new value to the end of a nsstring or nssdata every time the method is called. Any help would be greatly appreciated. I thought the property at the top would allow me to do it but it either only stores the last value or nothing at all. I am not used to the ways of objective c yet. Thanks.

Even this doesn't write anything to self.data:

NSString * result = [[requests valueForKey:@"value"]  componentsJoinedByString:@""];
NSData* data = [result dataUsingEncoding:NSUTF8StringEncoding];


[self.data appendData:data];

// Log it
NSLog(@"%@",self.data);

Solution

  • Remember kids when dealing with NSMutableData always initialize it!

    _data = [[NSMutableData alloc] init];
    

    This fixed the null problem for me.