Object-c学习之路四(oc内存管理autorelease)
2013-07-24 12:00 Lves Li 阅读(213) 评论(0) 收藏 举报
再以Student和Book为例作为展示:
1.主函数:
//  main.m
//  MemoryManagement2
//
//  Created by WildCat on 13-7-24.
//  Copyright (c) 2013年 wildcat. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Book.h"
#import "Student.h"
int main(int argc, const char * argv[])
{
    @autoreleasepool {
        Student *stu=[[[Student alloc] init] autorelease];
        Book *book=[[[Book alloc] init] autorelease];
        stu.book=book;
        
        
        Student *stu2=[Student student];
        Student *stu3=[Student studentWithAge:20];    
    }
    return 0;
}
2.Student函数:
// Student.h // MemoryManagement2 // // Created by WildCat on 13-7-24. // Copyright (c) 2013年 wildcat. All rights reserved. // #import <Foundation/Foundation.h> @class Book; @interface Student : NSObject #pragma mark - 属性定义 #pragma mark @property关键字的 用法 //nonatomic表示不支持多线程 atomic表示支持多线程 @property (nonatomic,retain) Book *book; @property (nonatomic,setter = isReach:) BOOL rich; @property (nonatomic,assign) int age; #pragma mark - 静态方法快速创建 +(id)student; +(id)studentWithAge:(int)age; @end
#import "Student.h"
#import "Book.h"
@implementation Student
#pragma mark - 销毁对象
-(void)dealloc{
    //销毁Book
    NSLog(@"Student %@ ,被销毁。",self);
    self.book=nil;
    [super dealloc];
}
#pragma mark - 静态方法快速创建对象
+(id)student{
    return [[[Student alloc] init] autorelease];
}
+(id)studentWithAge:(int)age{
    Student *stu=[self student];
    stu.age=age;
    return stu;
}
@end3.Book函数略
 
                    
                     
                    
                 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号