iOS的Copy

來源:互聯網
上載者:User

標籤:des   blog   使用   os   strong   io   for   div   

對象是在堆中的,堆只負責記憶體空間的劃分,這塊記憶體空間並沒有設定它的類型,任何類型的指標都可以指向這塊地址,但在XCode中不相容的類型會有黃色警告。

copy方法建立一個對象的副本(通常會多開闢一塊空間),但也有例外就是那些不可被改變的對象,比如NSString對象的copy方法,不會開闢新記憶體。

mutableCopy方法常用在將一個不可變類型的對象建立為一個可變類型的副本。比如

     NSString * str = @"hello";        NSMutableString * strM = [str mutableCopy];        [strM appendString:@"123"];        NSLog(@"%@",strM);

 copy方法不止能用來oc內建的類型上,只要遵守了NSCopying協議,並實現copyWithZone方法,那麼自訂對象也可以copy了。

Person.h

#import <Foundation/Foundation.h>@interface Person : NSObject <NSCopying>@property (nonatomic,copy) NSString * name;@property (nonatomic,strong) NSNumber * age;@end

 Person.m

#import "Person.h"@implementation Person- (id)copyWithZone:(NSZone *)zone{
  /**
  這裡用[self class]而不用Person的原因是方便繼承,這樣如果是使用的Student對象的copy方法,建立的便會是Student對象。
  */ Person * p = [[[self class] allocWithZone:zone]init]; p.name = self.name; p.age = self.age; return p;}- (NSString *)description{ return [NSString stringWithFormat:@"%@:%p %@ %@",[self class],self, self.name,self.age];}@end

 Student.h

#import "Person.h"@interface Student : Person@property (nonatomic,strong) NSNumber * No;@end

 Student.m

#import "Student.h"@implementation Student- (id)copyWithZone:(NSZone *)zone{    Student * s = [super copyWithZone:zone];    s.No = self.No;    return s;}-(NSString *)description{    NSString * str = [super description];    return [NSString stringWithFormat:@"%@ %@",str,self.No];}@end

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.