Reputation: 299
the code is:
typedef struct _Package
{
char* data;
int dataLen;
}Package;
Package *pack=(Package *)malloc(sizeof(pack));
pack->dataLen = 10;
pack->data = (char *)malloc(10);
strcpy(pack->data,"hellohello");
NSMutableArray *lstPack = [[NSMutableArray alloc] init];
[lstPack addobjec:pack];
when the program goto [lstPack addobject:pack],it cann't go on. If you know the reason,please tell me。
Thank you!
Upvotes: 0
Views: 235
Reputation: 95315
You can create a CFMutableArray
instead which can handle arrays of arbitrary objects, and you can use it as you would an NSMutableArray
(for the most part).
// create the array
NSMutableArray *lstPack = (NSMutableArray *) CFArrayCreateMutable(NULL, 0, NULL);
// add an item
[lstPack addObject:pack];
// get an item
Pack *anObject = (Pack *) [lstPack objectAtIndex:0];
// don't forget to release
// (because we obtained it from a function with "Create" in its name)
[lstPack release];
The parameters to CFArrayCreateMutable
are:
NULL
here means to use the default allocator.NULL
here, it means that you don't want the array to do anything with the values that you give it. Ordinarily for an NSMutableArray
, it would retain
objects that are added to it and release
objects that are removed from it¹, but a CFMutableArray
created with no callbacks will not do this.¹ The reason that your code is failing is because the NSMutableArray
is trying to send retain
to your Pack
struct, but of course, it is not an Objective-C object, so it bombs out.
Upvotes: 0
Reputation: 1
“… the result is that the p->data is nil …” — perhaps because of pack->dataLen = (char *)malloc(10);
I think, you wanted to do pack->data = (char *)malloc(10);
instead?
Greetings
Upvotes: 0
Reputation: 170829
You can add to obj-c containters (including NSMutableArray) only obj-c objects. To add a c-structure to array you can wrap it to NSValue object:
[lstPack addObject:[NSValue valueWithPointer:pack]];
Later you access stored value:
Package* pack = (Package*)[[lstPack objectAtIndex:i] pointerValue];
Note also that you possibly have a typo in that line - method name is incorrect.
Upvotes: 2