1

As Apple suggests, we need to check the index of an NSArray before calling objectAtIndex:. To do this, we can use a category or method swizzling.

For this subscript syntax,

index = 1;
id person = pArray[index];

is there a way to implement that? Of course, I can check index beforehand.

1
  • 2
    You want to check this for every array without opt out? That will add a lot of overhead and is definitely not need in most cases (for example when iterating over a range, or when the count is validated once after the array is received from the network or similar) Commented Feb 12, 2015 at 4:52

1 Answer 1

1

The compiler simply generates the fancy new syntax sugar into a call to objectAtIndexedSubscript:, so that would be the method you want to swizzle. As mentioned in my comment though, that will add a lot of overhead that you can't easily get out of after enforcing it.

Edit: One more thought on the overhead, NSArray already does that check internally and throws an exception when it comes out of bound. Maybe wrapping some blocks of code in @try/@catch blocks where it is sensible makes more sense for you?

Sign up to request clarification or add additional context in comments.

2 Comments

ah, objectAtIndexedSubscript is what I want~
no need to care about why the exception happens and hence abandon using @try/catch. If index is out of range, it gets a nil object which will be safe even sent a not found selector.

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.