OC重点--内存管理

内存管理:
    Student *student = [[Student alloc] initWithName:@"小王"];
    NSLog(@"%lu", [student retainCount]);//1

    MyClass *myClass = [[MyClass alloc] init];
    NSLog(@"%lu", [myClass retainCount]);//1
    
    [myClass setStudent:student];
    NSLog(@"%lu", [student retainCount]);//2
    NSLog(@"%lu", [myClass retainCount]);//1

    [student release];
    NSLog(@"%lu", [student retainCount]);//1
    NSLog(@"%lu", [myClass retainCount]);//1


    [myClass setStudent:student];
    NSLog(@"%lu", [student retainCount]);//1
    NSLog(@"%lu", [myClass retainCount]);//1


    Student *stu = [myClass student];
    NSLog(@"%lu", [student retainCount]);//2
    NSLog(@"%lu", [myClass retainCount]);//1
    
    [myClass release];
    NSLog(@"%lu", [student retainCount]);//1
//    NSLog(@"%lu", [myClass retainCount]);//crash
    [stu sayHi];
2015/2/9 19:36:08
儿子 2015/2/9 19:36:08

//    申请内存 逐一释放(每个人控制自己的开关)把下列输出里的stu换成stu1或者stu2也一样
    CollegeStudent *stu = [[CollegeStudent alloc] init];
    NSLog(@"retainCount = %lu", [stu retainCount]);//1
    
    CollegeStudent *stu1 = [stu retain];// 或者
    [stu1 retain];//如果有这一步,变成//1 //3 //4 //3 //2 //1
    NSLog(@"retainCount = %lu", [stu retainCount]);//2
    CollegeStudent *stu2 = [stu retain];
    NSLog(@"retainCount = %lu", [stu retainCount]);//3

    [stu2 release];
    NSLog(@"retainCount = %lu", [stu retainCount]);//2
    [stu1 release];
    NSLog(@"retainCount = %lu", [stu retainCount]);//1
    [stu release];
    NSLog(@"retainCount = %lu", [stu retainCount]);//1  //理论是0, 实际是1 在未来某一时刻自动释放
2015/2/9 19:39:44
儿子 2015/2/9 19:39:44

//    申请内存 逐一释放(每个人控制自己的开关)把下列输出里的stu换成stu1或者stu2也一样
    CollegeStudent *stu = [[CollegeStudent alloc] init];
    NSLog(@"retainCount = %lu", [stu retainCount]);//1
    
    CollegeStudent *stu1 = [stu retain];//功能和[stu1 retain]一样
    NSLog(@"retainCount = %lu", [stu retainCount]);//2
    
    [stu1 retain];
    NSLog(@"retainCount = %lu", [stu retainCount]);//3
    
    CollegeStudent *stu2 = [stu retain];
    NSLog(@"retainCount = %lu", [stu retainCount]);//4

    [stu2 release];
    NSLog(@"retainCount = %lu", [stu retainCount]);//3
    
    [stu1 release];
    NSLog(@"retainCount = %lu", [stu retainCount]);//2
    
    [stu release];
    NSLog(@"retainCount = %lu", [stu retainCount]);//1  //理论是0, 实际是1 在未来某一时刻自动释放

 

你可能感兴趣的:(OC重点--内存管理)