Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

objective c - Is it possible to filter an NSArray by class?

Is there a way construct a predicate to filter by class type?

I currently loop through the array and check to the class of each object. Maybe there is a cleaner way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can directly compare classes as well in your predicate.

But, it probably won't work as you would expect if you're trying to filter for objects that belong to class clusters or if you have subclasses.

For example, NSDate when instantiated is usually an __NSCFDate and NSString can be NSCFString as well as other specific private classes.

It's probably better to just loop through the set yourself and use -isKindOfClass: as the test.

IF you really want to use NSPredicate though you can do this. As an example, this would filter an array for all objects derived from NSString. If you wanted strict class membership you could replace isKindOfClass: with isMemberOfClass:.

Any selector that all objects in the collection implement, takes one argument and returns a BOOL should work though.

NSArray *mixedArray = {...};
NSPredicate *predicate = [NSPredicate predicateWithFormat:
                                      @"self isKindOfClass: %@",
                                      [NSString class]];

NSLog(@"%@", [mixedArray filteredArrayUsingPredicate:predicate]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...