ios Objective-C 字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5518658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C string arrays
提问by Namhcir
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.
2014 年更新:这篇文章中的代码现在实际上可以工作,因为框架和编译器中添加了特殊的语法支持,用于索引 NSArrays,如names[0]
. 但是在问这个问题的时候,它给出了这个问题中提到的错误。
回答by Catfish_Man
You don't use C array notation to access NSArray objects. Use the -objectAtIndex: method for your first example:
您不使用 C 数组表示法来访问 NSArray 对象。将 -objectAtIndex: 方法用于您的第一个示例:
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.
这样做的原因是 NSArray 不是“Objective-C 的一部分”。它只是 Cocoa 提供的一个类,很像您可以编写的任何类,并且没有特殊的语法特权。
回答by BoltClock
NSArray
is a specialized array class unlike C arrays. To reference its contents you send it an objectAtIndex:
message:
NSArray
是一个特殊的数组类,与 C 数组不同。要引用其内容,请向其发送objectAtIndex:
消息:
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 *
指针,而不是NSString
:
NSString *fileName = (NSString *)[names objectAtIndex:0];
回答by user454322
With the new Objective-C literals is possible to use:
使用新的 Objective-C 文字可以使用:
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 Subscriptingfor more information.
检查对象下标以获取更多信息。