iOS中copy的用法

来源:互联网 发布:澳门四季名店mac 编辑:程序博客网 时间:2024/04/29 23:40

1 深复制:内容拷贝,源对象和副本对象指的是两个不同的对象,源对象引用计数器不变,副本对象引用计数器为1

2 浅复制:指针拷贝,源对象和副本对象指的都是同一个对象,对象引用计数器+1,相当于retain

3 只有不可变对象创建不可变副本(copy)才是浅复制,其它的都是深复制


////  main.m//  CopyTest////  Created by Unisk on 13-9-20.//  Copyright (c) 2013年 Test. All rights reserved.//#import <Foundation/Foundation.h>#import "Student.h"#import "GoodStudent.h"#pragma mark copyvoid student(){    Student *stu1=[Student studentWithName:@"stu1"];    Student *stu2=[stu1 copy];    stu2.name=@"XZQ";    NSLog(@"%@",stu1);    NSLog(@"%@",stu2);    [stu2 release];}#pragma mark copyvoid goodStudent(){    GoodStudent *gtu1=[GoodStudent goodStudent:11 name:@"xzq"];    GoodStudent *gtu2=[gtu1 copy];    gtu2.age=111;    gtu2.name=@"google";        NSLog(@"%@",gtu1);    NSLog(@"%@",gtu2);    }int main(int argc, const char * argv[]){    @autoreleasepool {        goodStudent();    }    return 0;}

#import <Foundation/Foundation.h>@interface Student : NSObject<NSCopying>@property (nonatomic,copy) NSString *name;+(id)studentWithName:(NSString *)name;@end

////  Student.m//  CopyTest////  Created by Unisk on 13-9-20.//  Copyright (c) 2013年 Test. All rights reserved.//#import "Student.h"@implementation Student+(id)studentWithName:(NSString *)name{    Student *stu=[[[[self class] alloc] init] autorelease];    stu.name=name;    return stu;}#pragma mark 对象的拷贝-(id)copyWithZone:(NSZone *)zone{    Student *stu=[[[self class] allocWithZone:zone] init];    stu.name=self.name;    return stu;}-(NSString *)description{    return [NSString stringWithFormat:@"name is %@",_name];}- (void)dealloc{    [_name release];    [super dealloc];}@end

#import "Student.h"@interface GoodStudent : Student@property (nonatomic,assign) int age;+(id)goodStudent:(int) age name:(NSString *)name;@end

#import "GoodStudent.h"@implementation GoodStudent+(id)goodStudent:(int)age name:(NSString *)name{    GoodStudent *goodStu=[GoodStudent studentWithName:name];    goodStu.age=age;    return goodStu;}-(id)copyWithZone:(NSZone *)zone{    GoodStudent *gtu=[super copyWithZone:zone];    gtu.age=_age;    return gtu;}-(NSString *)description{    return [NSString stringWithFormat:@"name=%@,age=%i",self.name,_age];}@end


原创粉丝点击