4

Trying to cast the return of objectAtIndex.

(MyClass *)[myArray objectAtIndex:1].name;

Can you cast inline like this in Objective-C?

2 Answers 2

11

Yes you can:

((MyClass *)[myArray objectAtIndex:1]).name
Sign up to request clarification or add additional context in comments.

Comments

2

You can avoid casting altogether by replacing the dot-syntax of accessing properties with the regular method invocation syntax:

[[myArray objectAtIndex:1] name]

7 Comments

That will throw a warning though, and if you compile with ARC I think it may change to an error.
Yes this is a bad idea even if you are okay with the warning, if you remove the property name from MyClass you will continue to get a warning, but your app will crash and the code is hard to maintain this way...
@graver There's never a warning when you use this syntax: it's either an error, or a warning-free compile. When the identifier name does not correspond to a selector supported by any @interface in the system, an error is triggered. This approach works beautifully most of the time, and is a small price to pay for avoiding the need to provide an explicit cast.
@dasblinkenlight what you're saying is only valid when you're using ARC. I suppose you haven't developed apps prior ios5...
@graver Turning ARC off does not alter this behavior of the compiler: you do not get a warning when the identifier matches a selector of some object in the system, and you get an error when it does not match. I suppose there may be a bug in the compiler prior to LLVM that produces a warning, but that is not a good reason to avoid a perfectly valid syntax.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.