开启Xcode野指针调试功能:
1.点击左上角Stop按钮边上的项目名称
2.Edit Scheme
3.Diagnostics
4.勾选Objective—C的Enable Zoombie Objects
内存管理原则:
1.只要调用了alloc、new创建了一个新对象,那么就做一个relese
2.只要调用了retain,那么就做一次release
3.不能操作已经释放的对象,不让会发生也指针错误
4.在对象被释放之前,才能操作对象
5.计数器有加就有减
6.哪里alloc、new,哪里release
7.set方法的内存管理(设置的是对象)
release旧对象
retain新对象
- (void)setHouse:(House *)house{
if (house != _house) {
//扔掉旧房子
[_house release];
//对新房子做一次retain
_house = [house retain];
}
}
- (void)setCar:(Car *)c2
{
if (c2 != _car)
{
// release旧车
[_car release];
// retain新车
_car = [c2 retain];
}
}
- (Car *)car
{
return _car;
}
- (void)dealloc
{
[_car release];
[_house release];
NSLog(@"Person被销毁了!!!");
[super dealloc];
}
8.dealloc方法的内存管理
释放当前拥有的所有对象
9.@property的参数
一、控制set方法的内存管理:
1.retain:release旧值,retain新值
2.assign:直接赋值,不做任何内存管理(默认)
3.copy
二、控制有没有set方法和get方法
1.readwrite : 同时生成set和get方法(默认,少用)
2.readonly : 只会生成get方法
三、多线程管理
1.atomic : 性能低(默认)
2.nonatomic : 性能高
四、控制set方法和get方法的名称
1.setter : 设置set方法的名称,一定有个冒号:
2.getter : 设置get方法的名称
10.苹果官方提供的方法(API):
1)如果方法名不是alloc、new,就不用release或者autorelease
2)如果方法名是alloc、new,就必须release或者autorelease
协议:(可以遵守多个协议)
<>遵守某个协议,只要遵守了这个协议,相当于拥有协议里面的所有方法声明
编译器不强求实现协议里所有的方法
协议的应用--代理模式
代理的类型为id
-----------------------------
block:
1.定义block变量:
返回值类型 (^block变量名) (参数类型1, 参数类型2, ....);
2.给block变量赋值
block变量名 = ^(参数类型1 参数名称1, .....)
{
};
void test();
void test2();
// MyBlock其实就是新的数据类型名称
typedef int (^MyBlock)(int, int);
int main(int argc, const char * argv[])
{
test();
MyBlock minus = ^(int a, int b)
{
return a - b;
};
int d = minus(10,5);
NSLog(@"d id %d", d);
MyBlock sum = ^(int v1, int v2)
{
return v1 + v2;
};
int e = sum(10, 11);
NSLog(@"e is %d", e);
/*
int (^minusBlock) (int, int) = ^(int a, int b){
return a - b;
};
minusBlock(10, 5);
int (^averageBlock) (int, int) = ^(int a, int b)
{
return (a+ b)/2;
};*/
return 0;
}
void test()
{
int a = 10;
__block int b = 10;
//block内部不能修改默认是局部变量
//定义一个block变量
void (^block)() = ^{
b = 11;
NSLog(%@"b=%d",b);
};
block();
}
void test()
{
//左边的viod:block没有返回值
//右边的():没有参数
//中间的(^)block的标准,不能少
void (^myblock)() = ^{
int a = 11;
int b = 13;
NSLog(@"a=%d, b=%d",a,b);
};
myblock();
//定义一个block变量,变量名是sumBlock
//最左边的int:block的返回值是int类型
//最右边的(int, int) block接受连个int类型的参数
int (^sumBlock)(int,int);
sumBlock = ^(int v1, int v2) {
return v1 + v2;
};
int sum = sumBlock(10,11);
NSLog(%@"sum=%d",sum);
}