0

More for my interest than anything else.

If you have an Class defined like so...

MyClass
-------
NSString *name

And you put a lot of them into an array (or mutable array). Then you can use a predicate like this...

[NSPredicate predicateWithFormat:@"name = %@", someValue];

to filter the array so that it only contains objects whose names are the value given.

Or sort descriptor like so...

[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];

to sort the array by the name field in ascending order.

My question is, if you have an array of strings (or of NSNumbers) can you use similar "format" predicates?

Say for instance you had the array...

@[@"Cat", @"Bat", @"Dog", @"Cow"];

Could you use a "predicateWithFormat" to filter this array of a "sortDescriptorWithKey" to sort it?

I know you can use blocks but just wondering if this is possible?

2 Answers 2

1

Sure, you can filter an array of strings, or anything else, with predicateWithFormat:. As for sorting, you would use sortedArrayUsingSelector:, and use whichever selector you want (compare:, caseInsensitiveCompare:, etc.). There are no keys in a simple array, so you couldn't use sortDescriptorWithKey.

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

1 Comment

Ah! I always wondered what sortUsingSelector meant! That makes sense now. I've always used blocks for this and thought there must be an easier way. Thanks.
0

A string does not have any keys to use your predicates on or to sort by. You can find every other possible way to sort an array in the apple docs.

Comments

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.