标签:父类 hone ber 释放内存 就会 隐藏 例子 总结 core
{lock}
if (property != newValue) {
[property release];
property = [newValue retain];
}
{unlock}
- (void)setName:(NSString *)newName {
if (name != newName) {
[name release];
name = [newName retain];
// name’s retain count has been bumped up by 1
}
}
NSArray *array = [NSArray arrayWithObjects:@"hello",@"world",@"baby"];
NSArray *array2 = [array copy];
NSString *pt = [[NSString alloc] initWithString:@"abc"];
@property (nonatomic, assign) int number;
@property (nonatomic, copy) NSString * myString;
@property (nonatomic, retain) UIView *myView;
//接口文件
@interface MyClass : NSObject
@property (nonatomic, assign) int number;
@property (nonatomic, copy) NSString *myString;
@property (nonatomic, retain) UIView *myView;
@end
//实现文件
@implementation MyClass
@synthesize number;
@synthesize myString;
@synthesize myView;
//释放内存
- (void) dealloc {
[myString release]; //copy的属性需要release;
[myView release]; //retain的属性需要release;
[super dealloc]; //传回父对象
}
@end
MyClass *instance = [MyClass alloc] init];
// number赋值,没什么可说的, 简单数据类型就这样
instance.number = 1;
// 创建一个可变字符串
NSMutableString *string = [NSMutableString stringWithString:@"hello"];
instance.myString = string; //对myString赋值
[string appendString:@" world!"]; //往string追加文本
NSLog(@”%@”,string); //此处string已经改变, 输出为 “hello world!”
NSLog(@”%@”,instance.myString); // 输出myString,你会发现此处输出仍然为 “hello” 因为 myString在string改变之前已经copy了一份副本
UIView *view = [[UIView alloc] init];
NSLog(@”retainCount = %d”,view.retainCount);
// 输出view的引用计数, 此时为1
instance.myView = view; //对myView属性赋值
NSLog(@”retainCount = %d”,view.retainCount);
// 再次输出view的引用计数, 此时为2,因为myView对view进行了一次retain。
[view release];
// 此处虽然view被release释放掉了,但myView对view进行了一次retain,那么myView保留的UIView的对象指针仍然有效。
[instance release] ;
标签:父类 hone ber 释放内存 就会 隐藏 例子 总结 core
原文地址:https://www.cnblogs.com/CH520/p/10067701.html