-跟retain不同,⼀一個對象想要copy,⽣生成⾃自⼰己的副本,需要實現 NSCopying協議,定義copy的細節(如何copy)。如果類沒有接 受NSCopying協議⽽而給對象發送copy消息,會引起crash。
@implementation Person
- (id)copyWithZone:(NSZone *)zone{
Person *p = [[Person allocWithZone:zone]init];
p.age = self.age;
p.name = self.name;
return p;
}
@property(nonatomic,assign)NSString *name;
- (void)setName:(NSString *)name{
_name = name; }
- (NSString *)name{
return _name; }
@property(nonatomic,retain)NSString *name;
- (void)setName:(NSString *)name{
if(_name != name){ [_name release]; _name = [name retain];
} }
-(NSString *)name{
return [[_name retain]autorelease];
}
-(id)initWithName : ( NSString *)name
{
self = [super init];
if (self) {
self.name = name;
}
return self;
}
- (void)setName:(NSString *)name
{
if(_name != name)
{
[_name release];
_name = [name copy];
}
}
- (NSString *)name{
return [[_name retain]autorelease];
}
set 和get 方法只能重寫一個。
內存泄露
dealloc
永遠不要手動調用dealloc , dealloc 的最後一行必須要寫[super dealloc].
便利構造器:
return[p autorelease]
collection : 加入的對象自動retain , 移除的對象自動release ,本身釋放時,對內部所有的對象release 。
http://blog.csdn.net/jobtong/article/details/8453434
http://blog.csdn.net/chenzhiqin20/article/details/8497419http://www.douban.com/note/210192618/
NSString * str = [NSString stringWithFormat:@"asfpngyuipng"];
if ([str rangeOfString:@"png"].length > 0) {
str = [str stringByReplacingOccurrencesOfString:@"png" withString:@""];
}
NSLog(@"%@",str);
創建對象時,對象的內存分配在堆區,指向對象的指針分配在棧區,堆區內存需要程序員手動申請和釋放。
oc只允許單繼承,解決多繼承的方法是協議。(協議和代理)