1

I have a string array as such:

NSArray *names;
names = [NSArray arrayWithObjects:
@"FirstList",
@"SecondList",
@"ThirdList",
  nil];     

I'm trying to assign an element of this string array to a string variable as such:

NSString *fileName = names[0]; // "Incompatible types in initialization"

or with casting

NSString *fileName = (NSString)names[0]; // "Conversion to non-scalar type requested"

I'm trying to do this, so I can use the string in a method that takes a string as an argument, such as:

NSString *plistPath = [bundle pathForResource:filetName ofType:@"plist"];

Is there no way to assign an element of a string array to a string variable?

Update from 2014: The code in this post actually would work these days since special syntactic support has been added to the framework and compiler for indexing NSArrays like names[0]. But at the time this question was asked, it gave the error mentioned in this question.

3 Answers 3

8

You don't use C array notation to access NSArray objects. Use the -objectAtIndex: method for your first example:

NSString *fileName = [names objectAtIndex:0];

The reason for this is that NSArray is not "part of Objective-C". It's just a class provided by Cocoa much like any that you could write, and doesn't get special syntax privileges.

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

3 Comments

Thank you Catfish_Man. What does 'not "part of Objective-C" ' mean, if it is provided by Cocoa?
Objective-C is a language, like C++ or Java. Cocoa is a library, like .NET or the STL. Cocoa is written in Objective-C, and usable in Objective-C code, but it is not the same thing as Objective-C.
Also, because Objective-C doesn't provide operator overloading, Cocoa's collection classes can't provide [] support the way STL's std::vector (for example) does.
5

NSArray is a specialized array class unlike C arrays. To reference its contents you send it an objectAtIndex: message:

NSString *fileName = [names objectAtIndex:0];

If you want to perform an explicit cast, you need to cast to an NSString * pointer, not an NSString:

NSString *fileName = (NSString *)[names objectAtIndex:0];

Comments

0

With the new Objective-C literals is possible to use:

NSString *fileName = names[0];


So your code could look like this:

- (void)test5518658
{

 NSArray *names  = @[
         @"FirstList",
         @"SecondList",
         @"ThirdList"];

 NSString *fileName = names[0];

 XCTAssertEqual(@"FirstList", fileName, @"Names doesn't match ");

}

Check Object Subscripting for more information.

Comments

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.