Storing a C float array in an NSDictionary - ios

I am trying to store a c-float array in an NSDictionary to use later.
I was initially using an NSArray to store the C-data but NSArray is to slow for my intentions.
I am using the following code to wrap the arrays in the NSDictionary:
[self.m_morphPositions setObject:[NSValue valueWithBytes:&positionBuff objCType:#encode(float[(self.m_countVertices * 3)])] forKey:fourCC];
And retrieving the C-Float array using:
float posMorphs[(self.m_countVertices*3)];
NSValue *posValues = [self.m_morphPositions objectForKey:name];
[posValues getValue:&posMorphs];
When I retireve the array, the values are all set to 0.0 for each index which is wrong.
How can I fix this?

I also think that NSData is probably the best solution here. But just if anybody is interested: You cannot use #encode with a variable sized array, because it is a compiler directive. Therefore
#encode(float[(self.m_countVertices * 3)])
cannot work. Actually the compiler creates the encoding for a float array of size zero here, which explains why you get nothing back when reading the NSValue.
But you can create the type encoding string at runtime. For a float array,
the encoding is [<count>^f] (see Type Encodings), so the following would work:
const char *enc = [[NSString stringWithFormat:#"[%d^f]", (self.m_countVertices * 3)] UTF8String];
NSValue *val = [NSValue valueWithBytes:positionBuff objCType:enc];

NSValue is probably intented for scalar values, not arrays for them. In this case, using NSData should be much easier
NSData* data = [NSData dataWithBytes:&positionBuff length:(self.m_countVertices * 3 * sizeof(float))];
[data getBytes:posMorphs length:(self.m_countVertices * 3 * sizeof(float))];
Another solution is to allocate the array on the heap and use NSValue to store the pointer.

You can feed the bytes into an NSDictionary if they're wrapped in an NSData.
If you want to skip that, you would use an NSMapTable and NSPointerFunctionsOpaqueMemory (or MallocMemory) for the value pointer functions.

I'm not sure if it is the way you are encoding your value, but it might help to encapsulate your array into a struct.
// Put this typedef in a header
typedef struct
{
float values[3];
} PosValues;
In your code:
// store to NSValue
PosValues p1 = { { 1.0, 2.0, 3.0 } };
NSValue *val = [NSValue valueWithBytes:&p1 objCType:#encode(PosValues)];
// retrieve from NSValue
PosValues p2;
[val getValue:&p2];
NSLog(#"%f, %f, %f", p2.values[0], p2.values[1]. p2.values[2]);
The benefit to this approach is that your array is kept as an array type. Also, these structures are assignable even though raw arrays are not:
PosValues p1 = { { 1.0, 2.0, 3.0 } };
PosValues p2;
p2 = p1;

Related

Use NSValue to wrap a C pointer

I have a C type pointer variable:
a_c_type *cTypePointer = [self getCTypeValue];
How can I convert cTypePointer to NSObject type & vise versa?
Should I use NSValue? What is the proper way to do so with NSValue?
You can indeed use a NSValue.
a_c_type *cTypePointer = [self getCTypeValue];
NSValue * storableunit = [NSValue valueWithBytes:cTypePointer objCType:#encode(a_c_type)];
note that the 1st parameter is a pointer (void*). the object will contain the pointed value.
to get back to C:
a_c_type element;
[value getValue:&element];
Note that you would get the actual value, not the pointer. But then, you can just
a_c_type *cTypePointer = &element
Test it :
- (void) testCVal
{
double save = 5.2;
NSValue * storageObjC = [NSValue valueWithBytes:&save objCType:#encode(double)];
double restore;
[storageObjC getValue:&restore];
XCTAssert(restore == save, #"restore should be equal to the saved value");
}
test with ptr :
typedef struct
{
NSInteger day;
NSInteger month;
NSInteger year;
} CDate;
- (void) testCVal
{
CDate save = (CDate){8, 10, 2016};
CDate* savePtr = &save;
NSValue * storageObjC = [NSValue valueWithBytes:savePtr objCType:#encode(CDate)];
CDate restore;
[storageObjC getValue:&restore];
CDate* restorePtr = &restore;
XCTAssert(restorePtr->day == savePtr->day && restorePtr->month == savePtr->month && restorePtr->year == savePtr->year, #"restore should be equal to the saved value");
}
You simply use the method valueWithPointer: to wrap a pointer value as an NSValue object, and pointerValue to extract the pointer value.
These are just like valueWithInt:/intValue et al - they wrap the primitive value. You are not wrapping what the pointer points at. Therefore it is important that you ensure that when extract the pointer that whatever it pointed at is still around, or else the pointer value will be invalid.
Finally you must cast the extract pointer value, which is returned as a void *, back to be its original type, e.g. a_c_type * in your example.
(If you want to wrap what is being pointed at consider NSData.)
HTH

Get float value from NSData bytes

how can I write this
float value = *(float *)[data bytes];
in swift?
Thanks.
The corresponding Swift code is
let value = UnsafePointer<Float>(data.bytes).memory
which – as your Objective-C code – assumes that the NSData
objects has (at least) 4 bytes, representing a floating point value
in host byte order.
UnsafePointer<Float>(..) corresponds to the (float *) cast.
.memory corresponds to the dereferencing operator *.
An alternative is
var value : Float = 0
data.getBytes(&value, length: sizeofValue(value))

Float array to float *

What is the difference between float[] and float*?
Also, how can I convert a float array to float *? I need to get a float * and open it, then apply a filter and send it as a float * into my FFT method, but I don't know how to do it because I don't know the real difference between them.
An array usually is a pointer to the first member of the list. When using Array[Identifier], you are accessing to *(p+Identifier).
Making a new array will define a series of pointer next to another, which will make it's use way easier.
You can set your float array in the following ways:
float array1[100] = { 0 };
float *dataArray = (float*)malloc(sizeof(float) * 100);
float *pointerToFloatArray = array1;
These points all relate to C:
the name of an array can be decomposed — i.e. implicitly converted — to a pointer to its first element;
in an array, elements are stored contiguously;
the syntax a[8] is just shorthand for *(a + 8); and
adding n to a pointer, p, is defined to add n * sizeof(*p).
So an array differs from a pointer by being a semantically different thing. But you can supply the name of an array anywhere a pointer is required as it'll be converted.
Separately, you can also add an offset to any pointer using subscript syntax.
Objective-C is a strict superset of C. So these rules also apply to the use of the primitive types in Objective-C.
To understand the distinction, think in terms of mutability. The following is invalid:
char array[];
char value;
array = &value;
You can't reassign array. It is the name of an array. array itself is not mutable at runtime, only the things within it are. Conversely the following is valid:
char *pointer;
char value;
pointer = &value;
You can reassign pointer as often as you like. There's a mutable pointer and you can use it to point to anything.
You can use C-style arrays, like described in this answer: https://stackoverflow.com/a/26263070/3399208,
but better way - is using Objective-C containers and Objective-C objects, for example NSNumber * :
NSArray *array = [#1, #2, #3];
or
NSMutableArray *array = [NSMutableArray array];
NSNumber *number1 = [NSNumber numberWithFloat:20.f];
NSNumber *number2 = #(20.f);
[array addObject:number1];
[array addObject:number2];

ios assigning value to a string from an array

So I have a basic array:
NSMutableArray *answerButtonsArrayWithURL = [NSMutableArray arrayWithObjects:self.playView.coverURL1, self.playView.coverURL2, self.playView.coverURL3, self.playView.coverURL4, nil];
The objects inside are strings. I want to access a random object from that array
int rndValueForURLS = arc4random() % 3;
and assigning it a value. I've tried manny different approaches but my recent one is
[[answerButtonsArrayWithURL objectAtIndex:rndValueForURLS] stringByAppendingString:[self.coverFromRightAnswer objectAtIndex:self.rndValueForQuestions]];
Any help will be much appreciated. Thanks
You need to assign it. You're already building the new value like that:
NSString *oldValue = answerButtonsArrayWithURL[rndValueForURLS];
NSString *newValue = [oldValue stringByAppendingString:[self.coverFromRightAnswer objectAtIndex:self.rndValueForQuestions]];
The part you're missing :
answerButtonsArrayWithURL[rndValueForURLS] = newValue;
Above would be the way to replace the immutable string with another. If the strings are mutable, that is, they were created as NSMutableString, you could do:
NSMutableString *value = answerButtonsArrayWithURL[rndValueForURLS];
[value appendString:[self.coverFromRightAnswer objectAtIndex:self.rndValueForQuestions]];
Note:
Everywhere I replace the notation :
[answerButtonsArrayWithURL objectAtIndex:rndValueForURLS];
with the new equivalent and IMO more readable:
answerButtonsArrayWithURL[rndValueForURLS];

How to create an NSValue from the addition of a pointer and an integer?

I need to create a key for an NSMutableDictionary. The ideal key would be the merger of a pointer and an integer.
This will work for just the pointer
NSValue *key = [NSValue valueWithPointer:somePointer];
How do I add together somePointer + someInt and then form a key from the result?
I would do this:
NSObject *p = <object>
int n = 0xdeadbeef;
NSValue *v = [NSValue valueWithPointer:(void *)((uint32_t )p + n)];
NSLog(#"p = %p n = %x v = %#",p,n,v);
Pointers are integer types whose size depends on your platform (32 or 64 bits typically) which can be added to other integral types using a suitable cast. Just make sure to cast with a type whose length is greater than or equal to the length of a void pointer. This will ensure that you don't truncate the pointer.

Resources