store uint8_t in NSMutableArray

2.3k views Asked by At

in my program i am getting my receiving data from sensors in uint8_t type. I need to store those data in a NSMutable array.

i created a NSMutable array

NSmutableArray *test;

initialize it

test = [[test alloc]init];

Then i tried to store data in my array

[test addObject:Message.data7];

Message.data7 is in uint8_t format

But it want allow me to store like that way ,

Can any one explain me how to do that.

thanks in advance

4

There are 4 answers

3
neilco On BEST ANSWER

You can't store simple primitives in NSArray/NSMutableArray. However, you can convert it to a NSNumber and store that:

[test addObject:@(Message.data7)];

When you want to retrieve the value from the array:

uint8_t value = (uint8_t)[test[index] unsignedCharValue];
0
Anoop Vaidya On

Objective-C objects can store objects only.

unit8_t is not an obj-c object hence you can't add to NSArray.

You need to convert that value to some compatible type(any objective-c object) then you can store it.

uint8_t value = 10;
NSArray *array = @[@(value)]; //boxed to NSNumber, and added to array.

In your case:

[test addObject:@(Message.data7)];
1
slecorne On

You cannot store simple type inside NSMutableArray. You may only store objects.

You have 2 way of doing it, store NSNumber and convert them back to uint8_t when reading from the array or used a C array uint8_t array[]

0
Ivan Genchev On

uint8_t is defined as unsigned char in _uint_8_t.h so you can use NSNumber initWithUnsignedChar: and store that in the array and then use the unsignedCharValue and cast that back to uint8_t.