lqf
lqf

Reputation: 299

One problem of NSMutableArray

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

Answers (3)

dreamlax
dreamlax

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:

  1. The allocator to use for the array. Providing NULL here means to use the default allocator.
  2. The limit on the size of the array. 0 means that there is no limit, any other integer means that the array is only created to hold exactly that many items or less.
  3. The last parameter is a pointer to a structure containing function pointers. More info can be found here. By providing 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

“… 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

Vladimir
Vladimir

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

Related Questions