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) Advanced Objective-C Dynamic Typing

Dynamic Typing's Use?

If we have an array with different datatypes as showing the example. Why cant we simply use an array in the for loop as we have used in previous examples to retrieve the values. What is the use of id?

2 Answers

Thanks for your explanation. The use is relevant in your example than the video.

Michael Hulet
Michael Hulet
47,869 Points

id is used when you don't know what kind of object you're going to be dealing with, or if you're going to be dealing with multiple types of objects with the same code. Take this function, for example:

    NSLog(@"%@", object);

Yes, this function kind of reinvents the wheel, but bear with me. Specifying the object type as id allows us to do something like this:

[self logObjectToConsole:[[UIViewController alloc] init]];
[self logObjectToConsole:@"This is also an object"];

If we hadn't made the type the logObjectToConsole: function takes an id, then we only would've been able to log one type of object. For example, lets say I defined the above function like this:

-(void)logObjectToConsole:(NSArray *)object{
    NSLog(@"%@", object);

We'd only be allowed to pass in NSArrays, or one of their children (like an NSMutableArray). In other words, this would be legal:

[self logObjectToConsole:@[1, 2, 3]];

However, this would cause a compiler error:

[self logObjectToConsole:@"This is an NSString, not an NSArray"];