標籤: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