Set方法的代码规范
(1)基本数据类型:直接复制
-(void)setAge:(int)age
{
_age=age;
}
(2)OC对象类型
-(void)setCar:(Car *)car
{
//1.先判断是不是新传进来的对象
If(car!=_car)
{
//2 对旧对象做一次release
[_car release];//若没有旧对象,则没有影响
//3.对新对象做一次retain
_car=[car retain];
}
}
// Student.h
// 内存管理2-对象之间的内存管理
//
#import <Foundation/Foundation.h>
#import "Book.h"
@interface Student : NSObject {
Book *_book;
}
@property int age;
- (id)initWithAge:(int)age;
@property Book *book;
- (void)readBook;
@end
============================
// Student.m
// 内存管理2-对象之间的内存管理
#import "Student.h"
@implementation Student
#pragma mark - 生命周期方法
#pragma mark 构造方法
- (id)initWithAge:(int)age {
if ( self = [super init] ) {
_age = age;
}
return self;
}
#pragma mark 回收对象
- (void)dealloc {
// 释放Book对象
[_book release];
// [self.book release];
NSLog(@"student:%i 被销毁了", _age);
[super dealloc];
}
#pragma mark - getter和setter
// @synthesize book = _book;
// 如果自己手动实现了getter和setter,xcode就不会自动生成@synthesize
// 也就不会自动生成_book
// getter和setter的默认实现
- (void)setBook:(Book *)book {
if (_book != book) {
// 先释放旧的成员变量
[_book release];
// 再retain新传进来的对象
_book = [book retain];
}
}
- (Book *)book {
return _book;
}
#pragma mark - 公共方法
#pragma mark 读书
- (void)readBook {
NSLog(@"当前读的书是:%f", _book.price);
}
//#pragma mark - 私有方法
//#pragma mark 私有方法1
//- (void)test1 {
//
//
//}
//#pragma mark 私有方法2
//- (void)test2 {
//
//
//}
//#pragma mark 私有方法3
//- (void)test3 {
//
//
//}
@end
=============
//
// Book.h
// 内存管理2-对象之间的内存管理
#import <Foundation/Foundation.h>
@interface Book : NSObject
@property float price; // 价格
- (id)initWithPrice:(float)price;
@end
// Book.m
// 内存管理2-对象之间的内存管理
//
#import "Book.h"
@implementation Book
- (id)initWithPrice:(float)price {
if ( self = [super init] ) {
_price = price;
}
return self;
}
- (void)dealloc {
NSLog(@"book:%f 被销毁了", _price);
[super dealloc];
}
@end
// main.m
// 内存管理2-对象之间的内存管理
#import <Foundation/Foundation.h>
#import "Book.h"
#import "Student.h"
void test(Student *stu) {
// book:1
Book *book = [[Book alloc] initWithPrice:3.5];
// book:2
stu.book = book;
// book:1
[book release];
// book:1
stu.book = book;
stu.book = book;
// book2:1
Book *book2 = [[Book alloc] initWithPrice:4.5];
// book2:2
stu.book = book2;
// book2:2
stu.book = book2;
// book2:1
[book2 release];
// book2:1
stu.book = book2;
}
void test1(Student *stu) {
[stu readBook];
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
// stu:1
Student *stu = [[Student alloc] initWithAge:10];
// stu:1
// book:1
// book2:1
test(stu);
// stu:1
// book:1
// book2:1
test1(stu);
// stu:0
// book2:0
// book:1
[stu release];
// stu = nil; 清空stu这个指针,stu就会变成空指针
// [stu release]; // 野指针(会报错)
[nil release]; // 空指针(不会报错)
}
return 0;
}