3

As an example, instead of writing this:

NSArray *someArray = @[@"1", @"2", @"3", @"4"];
[someArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *aString = obj;
    // do something
}];

You can down-cast the object directly if you know the constants in the block method to make it more consice:

[someArray enumerateObjectsUsingBlock:^(NSString *aString, NSUInteger idx, BOOL *stop) {
    // do something
}];

Does this go against any best practices or oop principles?

Edwin Iskandar
  • 4,119
  • 1
  • 23
  • 24
  • 1
    Note that just like in the case of `void *`, you don't have to cast `id`. `NSString *aString = obj;` is just fine. –  Nov 16 '12 at 19:56
  • OMG! Revelation! I will definitely be using this in the future! – Fogmeister Nov 16 '12 at 20:13
  • @H2CO3 ah good point. I'll update the question for clarity – Edwin Iskandar Nov 16 '12 at 20:22
  • @EdwinIskandar See [this one](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) as well. –  Nov 16 '12 at 20:34
  • @EdwinIskandar I bet up until this time you had been doing terrible things like `char *str = (char *)malloc(size + 1);` ;-) –  Nov 16 '12 at 21:14
  • @EdwinIskandar Yep :P It's a typical beginner problem. Most beginners do not care about style, and "if it works it's more than perfect". In fact, readability, clarity and overall style is very important (I'd say it makes up about 25-30% of the overall code quality). –  Nov 16 '12 at 21:20

1 Answers1

4

I'm pretty sure that's fine. As long as you know what's in the array, feel free to statically type the id arguments. It's mostly syntactic sugar at the end of the day anyways. I always statically type anything I can. It helps me catch bugs as well as makes things easier to read. Also, as H2CO3 pointed out, objects can be assigned to an id and back without casts.

Metabble
  • 11,773
  • 1
  • 16
  • 29