无序的去重
- 利用NSDictionary的AllKeys(AllValues)方法
可以将NSArray中的元素存入一个字典,然后利用AllKeys或者AllValues取得字典的所有键或值,这些键或值都是去重的
NSArray *originalArray = @[@1, @2, @3, @1, @3];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSNumber *n in originalArray) {
[dict setObject:n forKey:n];
}
NSLog(@"dict: %@",[dict allValues]);
NSArray *originalArray = @[@1, @2, @3, @1, @3];
NSSet *set = [NSSet setWithArray:originalArray];
NSLog(@"result: %@", [set allObjects]);
有序的去重
- 1.开辟新的内存空间(使用containsObject:方法)
判断是否存在,若不存在则添加到数组中,得到最终结果的顺序不发生变化
NSArray *originalArray = @[@1, @2, @3, @1, @3];
NSMutableArray *resultArray = [NSMutableArray array];
for (NSString *item in originalArray) {
if (![resultArray containsObject:item]) {
[resultArray addObject:item];
}
}
NSLog(@"resultArray : %@", resultArray);
- 2.通过valueForKeyPath (@"@distinctUnionOfObjects.self")
NSArray *originalArray = @[@1, @2, @3, @1, @3];
NSArray *resultArray = [originalArray valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"result: %@", resultArray);
模型对象的去重
1.通过model类的唯一标识来判断
// Model.h
@interface Model : NSObject
@property (nonatomic, copy) NSString *ID;
@property (nonatomic, copy) NSString *name;
@end
// Model.m
@implementation Model
@end
//创建model类对象
Model *model1 = [[Model alloc]init];
model1.ID = @"1";
Model *model2 = [[Model alloc]init];
model1.ID = @"2";
Model *model3 = [[Model alloc]init];
model1.ID = @"3";
Model *model4 = [[Model alloc]init];
model1.ID = @"1";
Model *model5 = [[Model alloc]init];
model1.ID = @"3";
//添加到数组中
NSMutableArray *originalArray = [NSMutableArray arrayWithArray:@[model1,model2,model3,model4,model5]];
NSMutableArray *resultArray = [NSMutableArray arrayWithArray:originalArray];
//去重
for (NSInteger x = 0; x < originalArray.count; x++) {
for (NSInteger y = x+1;y < originalArray.count; y++) {
Model *tempModel = originalArray[x];
Model *model = originalArray[y];
if ([tempModel.ID isEqualToString:model.ID]) {
[resultArray removeObject:model];
}
}
}
NSLog(@"result: %@", resultArray);
网友评论