0

i have an array of 5 objects.

i want to assign object which is at index 1, to an NSSTRING.

nsstring *abc = [array objectAtindex:1];

i know this is wrong syntax, this is returning object , something like this.

how can i get value which is at index 1 and assign it to an string?

regards

4
  • What is the concrete question? Your code is ok and gets the 2nd item of the array. Commented Oct 17, 2010 at 14:16
  • @ Eiko ....is it?? but its giving <gfghf:767>, object not the value . Commented Oct 17, 2010 at 14:21
  • See the answers - the code is the same. Maybe it's a problem with the data itself, or the way you use it. Commented Oct 17, 2010 at 14:23
  • pheww..m going crazy on this..i hv an array with 5 objects..and when i am assinging it through these snippets its showing me <hghj:878>...crazzzzzy. Commented Oct 17, 2010 at 14:37

2 Answers 2

7

Erm.. this is the correct syntax :)

Apart the name of the string class:

NSString *abc = [array objectAtIndex:1];

mind that this won't create a copy of the string, if you need to copy it use

NSString *abc = [NSString stringWithString:[array objectAtIndex:1]];

As Eiko notes you can directly copy the string object if you need to:

NSString  *abc = [[array objectAtIndex:1] copy];
Sign up to request clarification or add additional context in comments.

5 Comments

Why not just [[array objectAtIndex:1] copy] ?
That's true, because I thought it would confuse him, let me add it
Copied your answer? what are you talking about? you also answered 2 minutes later than me. This is called whine and man, please, avoid being childish.
hi ,thanks for response...i quick question...my array on console showing this "<Coffee: 0x722f460>" but when i tried ur snippet, i am getting crash log saying..."[NSMutableArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]" what does dat even means? i hv objects in array, how can it be out of range??
because arrays are 0-based. This means that first element is at index 0, so use objectAtIndex:0 instead that 1.
2

Arrays are zero based in Objective-C land. So...

NSArray *array = [NSArray arrayWithObjects:@"one", @"two", nil];
NSString *abc = [array objectAtIndex:1];

Would return the second object in the array. Zero would return the first.

7 Comments

Why do you create an object in line 1 and throw it away in the 2nd?
@Jack: whatever other problems exist with this answer, a leak isn't one of them.
Well at least it has zero length and is autoreleased. It's a bug though and can easily break your code in a tight loop.
@Jack, We're not talking about a loop are we? First you copy my answer, then you vote me down, then you troll... nice.
@Jordan: let's assume -init instead that +string :)
|

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.