5

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.

Kazuki Sakamoto
  • 13,929
  • 2
  • 34
  • 96
Jay Zhao
  • 946
  • 10
  • 24
  • Why do you convert an already-working library to ARC? ARC is a per-file technology. – Yuji Sep 05 '11 at 12:52
  • How big is this library, really? Is it worth the hassle of dealing with C arrays and boxing/unboxing to work with the rest of your program? Most existing users won't particularly mind a conversion process on first launch (heck, Mail does that); new users won't have anything to convert. And you shouldn't be storing a large array into RAM either… – FeifanZ Sep 05 '11 at 13:06
  • Hi Yuji and Inspire48, Actually, the library is not an traditional library, it's https://github.com/booyah/protobuf-objc. The library will generate objective c source files based on *.proto files. And the generated *.m files will be included in my project directly, which is using ARC. I've tried using NSArray, but came up with tons of compile errors and cost me a whole day to fix that.So maybe the simplest way is to use id[]. – Jay Zhao Sep 05 '11 at 14:18

3 Answers3

11

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);
Kazuki Sakamoto
  • 13,929
  • 2
  • 34
  • 96
  • Thanks Kazuki Sakamoto, it works! But the params passing to calloc seems to be like this: – Jay Zhao Sep 05 '11 at 14:23
  • Oh, I fixed the 1st param for calloc. – Kazuki Sakamoto Sep 06 '11 at 04:45
  • Thanks for actually providing a useful and correct answer, rather than asking why. I just ran into this for new code, and was glad for the help. – Quinn Taylor Jul 31 '12 at 01:07
  • 2
    It's worth noting that zeroing the array (with calloc, bzero, memset, etc.) up front is critical, or ARC will try to release garbage non-zero values when you assign a value. (See http://stackoverflow.com/a/9119631/120292 for details.) Also, failing to nil out all values before freeing the array will result in a leak. – Quinn Taylor Jul 31 '12 at 06:08
1

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

__strong id idArray[20]; 
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
1

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);
Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94