views:

47

answers:

2

hi all, 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

+2  A: 

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.

Jordan
Why do you create an object in line 1 and throw it away in the 2nd?
Eiko
because leaks are cool!
Jack
Take it easy, wasn't finished editing the answer. Gee Whiz2
Jordan
@Jack: whatever other problems exist with this answer, a leak isn't one of them.
Graham Lee
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.
Eiko
@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
@Jordan: let's assume `-init` instead that `+string` :)
Jack
I didn't downvote you man, neither I copied you (I answered BEFORE you). take it easy.. it's StackOverflow, not a rush for the ultimate win
Jack
@Jordan Even after the edit, you're still unnecessarily creating an NSString object that you don't use. `NSString *abc = [NSString string];` creates an empty string and assigns it to `abc` but then you throw the empty string away in the third line.
kubi
@kubi, Correct. Edited.
Jordan
+1 jordon thankssss
shishir.bobby
+7  A: 

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];
Jack
Why not just [[array objectAtIndex:1] copy] ?
Eiko
That's true, because I thought it would confuse him, let me add it
Jack
-1 Because you copied my answer.
Jordan
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.
Jack
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??
shishir.bobby
because arrays are 0-based. This means that first element is at index 0, so use `objectAtIndex:0` instead that 1.
Jack
+1 jack thank a lot
shishir.bobby