Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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?


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.