NSMutableArray addobject with malloc'd struct

假如想象 提交于 2019-12-03 21:47:03

The proper way to do this is to encapsulate the data inside a NSValue, which is specifically for putting C types in NSArrays and other collections.

You can only add NSObject-derived objects to an array. You should encapsulate the data inside a proper object (for example NSData).

For example:

CLLocationCoordinate2D* new_coordinate = malloc(sizeof(CLLocationCoordinate2D));
    new_coordinate->latitude = latitude;
    new_coordinate->longitude = longitude;
    [points addObject:[NSData dataWithBytes:(void *)new_coordinate length:sizeof(CLLocationCoordinate2D)]];
    free(new_coordinate);

retrieving the object:

CLLocationCoordinate2D* c = (CLLocationCoordinate2D*) [[points objectAtIndex:0] bytes];

You can use the CFArrayCreateMutable function with custom callbacks to create a mutable array that doesn't retain/release.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!