Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Objective-C Basics (Retired) Foundation Framework NSDictionary

Harry Stromfelt
Harry Stromfelt
2,985 Points

How can you access all items in an array/dictionary, if the inputs are of different type?

The for loops that I have seen use for (NSString *item in theDictionaryORArray){} What would you do if you had some integers and strings stored in the same array? Or is that not possible?

Thanks!

2 Answers

You could use the regular for(;;) loop instead of the enumeration loop. The items in the array and dictionary must be objects though; can't put primitives in there. Then you would just print them out with %@ since it is a wrapper function that fetches the correct format depending on the type of object.

Alfian Losari
Alfian Losari
9,495 Points

I think you cannot put primitive data type such as int, float, bool to the NSArray, NSArray only accept object to add to the array. If you want to put int, float, bool data type you must use the NSNumber , and then add it to the NSArray. But be careful, if you have an NSArray containing NSString and NSNumber, then you cannot loop it using for (NSString *item in the NSArray), it will crash. Objective-C provide dynamic typing to reference to the value in the NSArray whatever the type of the objects are in the array by using id. You can use it like this. for (id item in yourArray) { NSLog("%@", item)}. %@ is used to reference to the value inside the according to the object descriptor method.