开发者

How to print a single array element in Objective-C?

How to print a array element at particular index in Objective-C? My code looks like this:

NSString *String=[NSString StringWithContentsOFFile:@"/User/开发者_StackOverflow中文版Home/myFile.doc"];
NSString *separator = @"\n";
NSArray *array = [String componetntsSeparatedByString:separator];
NSLog(@"%@",array);

I'm able to print the full contents of an array at once, but I want to assign the element at each index into a string, like...

str1=array[0];
str2=array[1];
str3=array[0];...this continues

How do I do this?


You want the objectAtIndex: method. Example:

NSString *str1 = [array objectAtIndex:0];
NSString *str2 = [array objectAtIndex:1];
NSString *str3 = [array objectAtIndex:2];

From the documentation:

objectAtIndex:
Returns the object located at index.

- (id)objectAtIndex:(NSUInteger)index

Parameters
index
An index within the bounds of the receiver.

Return Value
The object located at index.

Discussion
If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.


if this is only for debugging, you could try using po <> in the gdb.


As of clang version 3.3, you can use the [index] notation, so

NSString *str1 = array[0];

would work now. See here for details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜