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! While you're at it, check out some resources Treehouse students have shared here.

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) 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,913 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:

-(void)logObjectToConsole:(id)object{
    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"];