How to implement CHCircularBuffer in an iOS project?

for my iOS project for the game I need a ring buffer. It should work similarly to the queue in which elements exit and enter, but the total number of elements in the buffer should remain unchanged.

I have successfully implemented a ring buffer using java, but I am not so familiar with objective-c. I found a ring buffer implementation on the network called CHCircularBuffer: https://bitbucket.org/devartum/chdatastructures/src/4d6d7194ee94/source/CHCircularBuffer.m However, I could not execute it correctly.

A circular buffer is a property of a class called TerrainManager that performs all the mathematical generation of the terrain.

@interface TerrainManager : NSObject{ int terrainParts; CHCircularBuffer* circularTerrainBuffer; } @property(nonatomic, retain) CHCircularBuffer *circularTerrainBuffer; @end 

This is how the ring buffer is initialized in the TerrainManager implementation

 circularTerrainBuffer = [[CHCircularBuffer alloc] initWithCapacity:parts]; 

This creates an instance of the buffer and sets the size property for the parts. Now I add objects to the buffer using the addObject method:

 [circularTerrainBuffer addObject:[NSNumber numberWithDouble:0.2]]; 

Sometimes this line gets the error "exec_bad_access". For example. when I run the buffer with a capacity of 15, everything is fine, with 20 I get an error.

Now I'm trying to access the buffer from the terrain class where the drawing is executed. But whenever I try to access objects, I get a bad_access error.

 NSArray *arr = [terrainManager.circularTerrainBuffer allObjects]; 

eg. this line will create an error.

So something is wrong with my code. Perhaps I do not understand the buffer and add objects in a wrong way. I dont know. Any ideas or suggestions?

+7
source share
1 answer

Excerpts of the code you show are correct. I completed a small project to test the CHCircularBuffer way you specify and it works correctly. So the problem should be somewhere else.

The only way around this is IMHO, put a breakpoint on the line that crashes, and enter the addObject function to see exactly where it fails. The array can be redistributed there, so it may crash and provide poor access. The same goes for allObjects .

In any case, I must say that I can run my test without any problems, add objects, remove them from the head and tail and get an array of all objects without problems.

If you post more code, we can help a little more.

+3
source

All Articles