View Full Version : simple type cast in a loop?
mlecho
Aug 1, 2009, 12:41 PM
Sorry all, i am new to ObjectiveC-> In other programming languages, i like to cast the variable i am working with when in a loop. I have a class (FeedItem) with a property 'description' . I know that my NSMutableArray (menuList) has 15-20 of these FeedItem pushed earlier in my code (i can also see them in the debugger). However, when i prepare to do this loop, i get an error: "error: incompatible types in initialization"
why can't i do this?
for(int b =0;b<[menuList count];b++)
{
FeedItem *fi = menuList[b];
NSLog(@"----->@%",fi.description);
}
again, i am new to objective c, so is it my loop syntax?
Guiyon
Aug 1, 2009, 12:48 PM
Assuming that menuList of of type NSArray*, you cannot use the standard bracketed index method to access its elements; you must use the objectAtIndex: method.
For example, say I have an array NSArray *foo with three elements, @"zero", @"one" and @"two" (at their respective indices). Executing the snippet NSLog( @"%@", [foo objectAtIndex:0] ); will print "zero" to the console.
kainjow
Aug 1, 2009, 12:59 PM
If you don't need backwards compatibility, the preferred way to loop through an array is:
for (FeedItem *fi in menuList)
{
NSLog(@"----->@%",fi.description);
}
mlecho
Aug 1, 2009, 04:39 PM
thanks guys...both are perfect, and now this new-b can get back on track
Eraserhead
Aug 2, 2009, 10:13 AM
If you don't need backwards compatibility, the preferred way to loop through an array is:
for (FeedItem *fi in menuList)
{
NSLog(@"----->@%",fi.description);
}
Just like C#, nice :).
lee1210
Aug 2, 2009, 12:56 PM
Just like C#, nice :).
And Java, and Perl, and...
http://en.wikipedia.org/wiki/Foreach
It was something that was definitely missing from Objective-C, and a very welcome addition to 2.0.
-Lee
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.