Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...