Henry F
Henry F

Reputation: 4980

Putting NSData into an NSArray

I have NSData objects storing data (non character / non-ascii). I'm trying to put it into an array without it being interpreted as characters or ascii. I know this question has been asked a few times before, but none of the solutions posted have worked for me in this situation. I'm trying to avoid using property lists, which is what most answers suggested. I already tried converting the NSData to an NSString, then storing the string in the array, but of course it is interpreted as characters after putting it in the string, regardless of the encoding I've used. For example, one of the NSData's contains the value 2c, and when I put it into a string it is interpreted as ,. Does anyone know how I can store the raw data, in its original state, in an NSArray? Maybe by storing the data in user defaults, then somehow storing the defaults in an array? I'm at a loss.

Here is some possibly relevant code:

NSData *receivedData = [bleDevice readData];
NSString *receivedDataString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
[dataArray insertObject:receivedDataString atIndex:0];

When I call: [dataArray insertObject:receivedDataString atIndex:0]; It will store something like 2c ad a ,.

But, when I try and insert the raw data, like: [dataArray insertObject:receivedData atIndex:0]; It will simply not store anything. There are no warnings, no errors. I'll NSLog the array and it is null.

Upvotes: 1

Views: 3273

Answers (1)

Hot Licks
Hot Licks

Reputation: 47699

[dataArray insertObject:receivedData atIndex:0]; most certainly will insert "receivedData" into "dataArray" (so long as both exist). "receivedData" can be any sort of NSObject -- need not be a string. If the array is "null" when you log it then the array itself never got created.

(It's important to remember that if an object pointer is nil then method calls on that pointer do not fail but rather silently return zero/nil, so "returns nil" strongly suggests the object never was created.)

Upvotes: 3

Related Questions