Search code examples
objective-cpointersstorageprimitive

how to create and allocate a C buffer as part of an objective C class


best to explain with an example:

in my AudioItem.h

#define ITEM_CAPACITY 100

typedef struct DataStruct {
    void *                          content;
    UInt32                          size;
} DataStruct;

typedef DataStruct *DataStructRef;

@interface AudioItem : NSObject
{        
    DataStructRef data;        
}

@property (assign, readwrite) DataStructRef data;

in AudioItem.m @synthesize data;

-(id)initWithID:(NSString *)itemID
{
    self = [super init];        
    data->content = malloc(ITEM_CAPACITY);
    return self;
}

The above code looks a lot like this one, but I get a BAD_EXEC_ERROR.. how come? The reason why I would like to use a C buffer rather than some NSMutableData or whatever is b/c I've tried using NSMutableData and I feel like it's slowing down my real time application


Solution

  • it fails because data is a null pointer when you set its content.

    the easy way to do this is:

    enum { ITEM_CAPACITY = 100 };
    
    typedef struct DataStruct {
        char content[ITEM_CAPACITY];
        UInt32 size;
    } DataStruct;
    
    @interface AudioItem : NSObject
    {        
    @private
        DataStruct data;
    }
    
    @implementation AudioItem
    - (id)initWithID:(NSString *)itemID
    {
        self = [super init];
        if (0 == self) return;
        data.size = ITEM_CAPACITY;
        return self;
    }