Is it advisable to type the object in an array block enumeration whose type is known?

58 Views Asked by At

If I know what type of objects I am storying in my array, is it better to type it as such in the block enumeration or no?

Instead of:

[myClassArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { }];

Use this:

[myClassArray enumerateObjectsUsingBlock:^(MyClass *obj, NSUInteger idx, BOOL *stop) { }];
2

There are 2 best solutions below

0
On

As long as you aren't reassigning the array, you should be fine. Obviously it's better practice to set up a check to make sure if there is any doubt. The enumerateObjectsUsingBlock functions the same as a for(MyClass *obj in myClassArray) so you would only use the enumerate method if you wanted to take advantage of it's extra features. If you would describe the object as MyClass in the for loop circumstance, you might as well in the enumeration.

0
On

Personally I would always specify the type of the object in the block parameters of the enumerate method. And I would do the same for the NsDictionary equivalent method, by specifying the type of the key and the value.

I would, however, only do this if I can be certain of the types of the objects in the collection.

If you don't specify the type in the block parameters, then you will have to cast the id obj to another type inside the block, which is afaiac unnecessary.

Even if you can't be certain of the type of object in your collection (which you almost always can be), I would still prefer the object to have a type specified in the parameters and then confirm it inside the block with an NSAssert (and an if to fail safely in release builds).

There are other languages out there that provide the ability to declare methods in such a way to demand the type of object in the block was the same type as the objects in the collection. Since Obj-C doesn't allow this, I personally think it's better to always be explicit about what you expect to receive in a block such as the one you described.