Writing a structure to NSMutableArray

I have a game object that is processed in two completely different places. In the Contact Listener, I check some conditions, and if they happen, I have to save one or more parts of the complex data. So I decided to use struct. For instance:

struct SomeStruct { int value1; int value2; CGPoint value3; b2Vec2 value4; }; typedef SomeStruct SomeStruct; 

In the game scene, I look through all the game objects, and if its stack / array is not empty, do something and wipe it.

In Contact Listener, it repeats from the very beginning.

I have to use this architecture because of the strict order of execution (the method must be called after other methods).

I suspect that I need something like a vector or NSMutableArray (I think it will not work with the structure), so vector may be the only way.

But I donโ€™t understand how to achieve this. Can you help me with a code / pseudo-code or a link to a book / article where I can find a solution?

+4
source share
2 answers

There are many solutions to this problem.

  • Do not use struct . The obj-c class is almost the same as the structure.
  • Use CFArray ( CFArrayCreateMutable ) and put it there as a pointer.
  • Use a C ++ class with an STL vector.
  • Use the C array ( SomeStruct[] ) and increase its length when you need it.
  • Use the classic stack implementation with a linked list (each structure has a pointer to the next value).
+2
source

Cocoa provides the NSValue class for this purpose:

Creates an object that can be added to NSMutableArray :

 NSValue *someObj = [NSValue valueWithBytes:&myStruct objCType:@encode(SomeStruct)]; 

You can use [someObj pointerValue] to access void* , which represents the address of the structure you put in NSValue .

+3
source

Source: https://habr.com/ru/post/1393948/


All Articles