4

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

NSString *String=[NSString StringWithContentsOFFile:@"/User/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?

1
  • hey i got the answer ... sorry ....its NSLog(@"%@",[array objectAtIndex:index]); Commented Feb 5, 2010 at 6:36

3 Answers 3

7

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.

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

2 Comments

hey ya.. thanks... But do we have any function to knw how many array elements are there in an array. , because i need to put each one of array element in a string, then do some operation with the string, then again take the next array element into same string and perform some operation on the string... likewise goes on. so i thought of using a for loop. , hence for termination condition in for loop, what should be written? help me. its like for(int n=0; n<**??what to write here**;n++) { NSString *string = [array objectAtIndex:n]; // do some operation }
Hey.. No problem.. I got the solution for it :)
0

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

Comments

0

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

NSString *str1 = array[0];

would work now. See here for details.

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.