zoukankan      html  css  js  c++  java
  • ObjectiveC 对象复制 迎客

    Foundation系统对象(NSString,NSArray等)

    只有遵守NSCopying 协议的类才可以发送copy消息
    只有遵守 NSMutableCopying 协议的类才可以发送mutableCopy消息

    copy和mutableCopy区别就是copy返回后的是不能修改的对象, 而mutableCopy返回后是可以修改的对象。

    这个两个方法复制的对象都需要手动释放。

    自义定义Class

    自义定Class也需要实现NSCopying协义或NSMutableCopying协议后,其对象才能提供copy功能。

    代码
    //TestProperty.h
    #import <Cocoa/Cocoa.h>


    @interface TestProperty : NSObject
    <NSCopying>{
    NSString
    *name;
    NSString
    *password;
    NSMutableString
    *interest;
    NSInteger myInt;
    }

    @property (retain,nonatomic) NSString
    *name,*password;
    @property (retain,nonatomic) NSMutableString
    *interest;
    @property NSInteger myInt;

    -(void) rename:(NSString *)newname;

    @end

    //TestProperty.m
    #import "TestProperty.h"


    @implementation TestProperty

    @synthesize name,password,interest;
    @synthesize myInt;

    -(void) rename:(NSString *)newname{
    // 这里可以直接写成
    // self.name = newname;
    //
    if (name != newname) {
    [name autorelease];
    name
    = newname;
    [name retain];
    }
    }

    -(void) dealloc{
    self.name
    = nil;
    self.password
    = nil;
    self.interest
    = nil;
    [super dealloc];
    }
    - (id)copyWithZone:(NSZone *)zone{
    TestProperty
    *newObj = [[[self class] allocWithZone:zone] init];
    newObj.name
    = name;
    newObj.password
    = password;
    newObj.myInt
    = myInt;
    //深复制
    NSMutableString *tmpStr = [interest mutableCopy];
    newObj.interest
    = tmpStr;
    [tmpStr release];

    //浅复制
    //newObj.interest = interest;
    return newObj;
    }
    @end
  • 相关阅读:
    jsp登录显示
    flask 分页
    module pip has no attribute main
    html active属性
    Centos7配置
    python爬虫笔记----4.Selenium库(自动化库)
    python爬虫笔记
    python报错记录
    mybatis逆向文件
    python简单验证码
  • 原文地址:https://www.cnblogs.com/pengxl/p/1921646.html
Copyright © 2011-2022 走看看