Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

pointers - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...