LEO
LEO

Reputation: 2612

Stick NSString[] into NSArray

Why can't I stick NSString[] into NSArray? I get the following error "Implicit conversion of an indirect pointer to an Objective-C pointer to 'id' is disallowed with ARC"

Here's the code:

NSString *s1, *s2;
NSString *cArray[]={s1, s2};
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
[dataArray addObject:cArray];

Upvotes: 2

Views: 872

Answers (2)

Chuck
Chuck

Reputation: 237010

NSArray holds objects. A C array is not an object, so you can't put it in an NSArray. If you want to create an NSArray out of a C array, you can use the arrayWithObjects:count: constructor.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

You cannot do it, because the ownership of cArray cannot be transferred.

If it is a local variable, it would disappear as soon as its scope ends, leaving your mutable array with a dangling reference.

Even if it is a global, there would be a problem, because your NSMutableArray would not know how to release the C array properly.

Objective C wants to protect you from situations like that as much as possible, providing nice classes such NSArray to make your job easier:

NSMutableArray *dataArray = [NSMutableArray array];
NSString *s1 = @"hello", *s2 = @"world";
// You can choose another constructor as you see fit.
NSArray *cArray = @[s1, s2];
[dataArray addObject:cArray];

Upvotes: 3

Related Questions