在数组中使用KVC能达到过滤的效果。
以下为一个实例:
Book.h 的代码文件如下:
#import <Foundation/Foundation.h>
@class Book;
@interface Student : NSObject
@property (nonatomic,strong) NSArray *books;
@end
Book.m 的代码文件如下:
#import "Book.h"
@implementation Book
@end
Student.h 的代码文件如下:
#import <Foundation/Foundation.h>
@class Book;
@interface Student : NSObject
@property (nonatomic,strong) NSArray *books;
@end
Student.m 的代码文件如下:
#import "Student.h"
#import "Book.h"
@implementation Student
@end
main.m 的代码文件如下:
#import <Foundation/Foundation.h>
#import "Student.h"
#import "Book.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Book *book1 = [[Book alloc] init];
book1.name = @"红楼梦";
book1.age = 10;
Book *book2 = [[Book alloc] init];
book2.name = @"三国演义";
book2.age = 12;
Book *book3 = [[Book alloc] init];
book3.name = @"水浒传";
book3.age = 13;
NSArray *array = [NSArray arrayWithObjects:book1,book2,book3,nil];
Student *stu = [[Student alloc] init];
stu.books = array;
NSLog(@"----------方法1过滤后的输出----------");
//数组中的属性过滤:形式1
NSArray *array1 = [stu valueForKeyPath:@"books.name"];
for (NSString *name in array1) {
NSLog(@"book.name = %@",name);
}
NSLog(@"----------方法2过滤后的输出----------");
//数组中的属性过滤:形式2
NSArray *array2 = [array valueForKey:@"name"];
for (NSString *name in array2) {
NSLog(@"book.name = %@",name);
}
}
return 0;
}
测试结果:
2015-08-10 19:19:39.115 Demo2[36297:261287] ----------方法1过滤后的输出----------
2015-08-10 19:19:39.117 Demo2[36297:261287] book.name = 红楼梦
2015-08-10 19:19:39.117 Demo2[36297:261287] book.name = 三国演义
2015-08-10 19:19:39.117 Demo2[36297:261287] book.name = 水浒传
2015-08-10 19:19:39.117 Demo2[36297:261287] ----------方法2过滤后的输出----------
2015-08-10 19:19:39.118 Demo2[36297:261287] book.name = 红楼梦
2015-08-10 19:19:39.118 Demo2[36297:261287] book.name = 三国演义
2015-08-10 19:19:39.118 Demo2[36297:261287] book.name = 水浒传
在数组中使用KVC就到此为止了!