对象是在堆中的,堆只负责内存空间的划分,这块内存空间并没有设置它的类型,任何类型的指针都可以指向这块地址,但在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