id array member instance under ARC

2019-04-29 13:43发布

问题:

I want to write something like this:

@interface Foo{

    __strong id idArray[]; 

}
@end

But the compiler complains about it:

Field has incomplete type '__strong id []'.

How can I create an id array member instance under ARC? And how do I init that array? Using malloc? new[]?

I don't want to use NSArray because I'm converting a large library to ARC and that will cause a lot of work.

回答1:

If you want to allocate dynamically the array, use pointer type of id __strong.

@interface Foo
{
    id __strong *idArray;
}
@end

Allocate the array using calloc. id __strong must be intialized with zero.

idArray = (id __strong *)calloc(sizeof(id), entries);

When you are done, you must set nil to the entries of the array, and free.

for (int i = 0; i < entries; ++i)
    idArray[i] = nil;
free(idArray);


回答2:

You have to specify an array size, e.g.:

__strong id idArray[20]; 


回答3:

Either you give the array a fixed size:

__strong id idArray[20];

or you use a pointer and malloc:

__strong id *idArray;

...

self.idArray = calloc(sizeof(id), num);