4

Can I add a C array into a objective-C NSArray?

NSArray * testArray = [NSArray arrayWithObjects:
         @"obj1", 
         {"C array obj1", "C array obj2"},
          nil];

gives me Expected Expression message error.

1 Answer 1

4

You cannot add plain C arrays to NSArray.

But as storing a C array means storing a pointer, you can wrap that pointer into an NSValue and store that instead:

char *someCArray = ...;
NSArray *array = @[[NSValue valueWithPointer:someCArrray]];

Keep in mind that you are only storing the pointer - and memory management is still up to you.

Or you could wrap the memory of the array into some Objective-C object, like NSData, but there should be very good reasons to go to such lengths.

My guess in the wild is - without knowing the concrete use case - that you're better of converting the C data into objects themselves and store them "the Objective-C" way.

Sign up to request clarification or add additional context in comments.

3 Comments

Is there an inline notation so that I don't need to declare the variable someCarray?
@Patrick Where does the array come from, then? Some code must create it (and allocate its memory) - you certainly don't want to store a pointer to a short-lived slice of stack memory. And if you're just creating it, the question is, why use a C array here?
@dasblinkenlight Indeed bad wording on my part. Will edit the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.