iOS学习笔记(三十七)————深浅拷贝与谓词

/ 0评 / 0

即copy 与 mutablecopy,浅拷贝拷贝指针,深拷贝拷贝才是拷贝对象,copy是不可变的拷贝,mutablecopy是可变拷贝

     NSString *str = [NSString stringWithFormat:@"hello"];
     NSString *str1 = [str copy];
     NSMutableString *str2 = [str mutableCopy];
     [str2 appendString:@"world"];
     NSLog(@"%p %p %p",str,str1,str2);
     NSLog(@"%@ %@ %@",str,str1,str2);

copy过后得到对象为不可变类型,mutablecopy过后得到结果是可变类型
不可变类型进行不可变拷贝浅拷贝,其余都是深拷贝
上面规则仅仅限于系统遵循NSCopying协议以及NSMutableCopying协议
也就是NSString NSArray NSDictionary NSSet以及其子类
对象想要进行不可变拷贝需要实现NSCopying协议
对象想要进行可变拷贝需要实现NSMutableCopying协议

@interface People : NSObject
@property (nonatomic,strong) NSString *name;
@end

@implementation People

- (id)copyWithZone:(NSZone *)zone{
    //self代表拷贝前的对象
    NSLog(@"copyWithZone:%p",self);
    
    /*
     直接返回self是浅拷贝
     但是大家一般不这么做,因为毫无意义
     
     */
    //    return self;
    
    People *people = [[People alloc] init];
    people.name = self.name;
    return people;
}

- (id)mutableCopyWithZone:(NSZone *)zone{
    People *people = [[People alloc] init];
    people.name = self.name;
    return people;
}

@end

    People *people = [[People alloc] init];
    people.name = @"张三";
    People *people1 = [people mutableCopy];
    people.name = @"李四";
    NSLog(@"%p %p",people,people1);
    NSLog(@"%@ %@",people.name,people1.name);

OC中的谓词操作是针对于数组类型的,他就好比数据库中的查询操作,数据源就是数组,这样的好处是我们不需要编写很多代码就可以去操作数组,同时也起到过滤的作用,我们可以编写简单的谓词语句,就可以从数组中过滤出我们想要的数据。非常方便

    People *people = [[People alloc] init];
    people.name = @"张三";
    people.age = 21;
    
    People *people1 = [[People alloc] init];
    people1.name = @"张四";
    people1.age = 12;
    
    People *people2 = [[People alloc] init];
    people2.name = @"三张";
    people2.age = 15;
    
    People *people3 = [[People alloc] init];
    people3.name = @"李四";
    people3.age = 7;
    
    NSArray *arr = @[people,people1,people2,people3];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like '*张*' and age > 20"];
    NSArray *arr1 = [arr filteredArrayUsingPredicate:predicate];
    //    for (People *people in arr1) {
    //        NSLog(@"%@ %d",people.name,people.age);
    //    }
    
    
    
    NSArray *arr2 = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        People *p1 = obj1;
        People *p2 = obj2;
        if (p1.age < p2.age) {
            return NSOrderedAscending;
        }else{
            return NSOrderedDescending;
        }
        
    }];
    for (People *people in arr2) {
        NSLog(@"%@ %d",people.name,people.age);
    }

代码请查看 http://git.oschina.net/zcb1603999/LearningiOS

评论已关闭。