(1)当使用alloc、new或者copy创建一个对象时,对象的引用计数器被设置为1;
(2)给对象发送一条retain消息,对象的引用计数器+1;
(3)给对象发送一条release消息,对象的引用计数器-1;
(4)当一个对象的引用计数器的值为0时,OC会自动发送一条dealloc消息,收回其占用的内存,所以一般需要重写dealloc方法,释放相关资源;
(5)可以给对象发送retainCount消息获得当前引用计数器的值。
//Book.h
#import <Foundation/Foundation.h>
@interface Book : NSObject
@property float price;
@end
//Book.m
#import "Book.h"
@implementation Book
- (void)dealloc {
NSLog(@"destroy the book which costs $%0.2f", _price);
[super dealloc];
}
@end
//Student.h
#import <Foundation/Foundation.h>
@class Book;
@interface Student : NSObject
@property Book *book;
@end
//Student.m
#import "Student.h"
#import "Book.h"
@implementation Student
- (void)dealloc {
NSLog(@"destroy student");
[_book release];
_book = nil;
[super dealloc];
}
@synthesize book = _book;
#pragma mark - setter and getter //pragma mark是Xcode的标记功能,-表示分组
#pragma mark setter
- (void)setBook:(Book *)book {
if (_book != book) {
[_book release];
_book = [book retain];
}
}
#pragma mark getter
- (Book *)book {
return _book;
}
@end
//main.m
#import <Foundation/Foundation.h>
#import "Student.h"
#import "Book.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu = [[Student alloc] init];
Book *book1 = [[Book alloc] init];
book1.price = 35.5;
stu.book = book1;
[book1 release];
Book *book2 = [[Book alloc] init];
book2.price = 57.5;
stu.book = book2;
[book2 release];
[stu release];
}
return 0;
}