关于内存的管理

一、有关内存管理的一些方法:

retain、release、retainCount、alloc、new、autorelease、dealloc、drain;

retain、release、retainCount、alloc等方法在上文中已经做了介绍,这里不再赘述,下面介绍其他几个方法的使用:

1、new的使用和alloc相似,假设有一个类Class,那么[Class new]和[[Class alloc] init]等价,即创建一个对象,并对他初始化;

2、autorelease是推迟回收对象的一个方法,假设有一对象p,在执行语句[p  autorelease]后,不会立即回收对象,会等到执行@autoreleasepool{}的“}”后或者执行到[pool release]或者[pool  drain]后回收,其中pool为NSAutoreleasepool*类型的对象;

3、drain和release类似,用于[pool drain]以回收内存;

4、dealloc方法在对象被回收之前执行,在dealloc方法之外不能调用,且只能用super调用;

5、copy、new、create、alloc开头的方法引用计数为1。

 

 

main.m

 1 #import <Foundation/Foundation.h>
 2 #import "ClassOne.h"
 3 #import "ClassTwo.h"
 4 #import "ClassThree.h"
 5 
 6 int main(int argc, const char * argv[])
 7 {
 8 
 9     @autoreleasepool {
10         ClassThree *s=[[ClassThree alloc] initClassThree];
11         [s autorelease];
12         [s print];
13        
14     }
15     return 0;
16 }

 

 

classone.h

#import <Foundation/Foundation.h>
#import "ClassTwo.h"

@interface ClassOne : NSObject
{
    ClassTwo *p;
}


@end

 

 

 

classone.m

 1 #import "ClassOne.h"
 2 #import "ClassTwo.h"
 3 
 4 @implementation ClassOne
 5 - (void)dealloc
 6 {
 7     [p release];
 8     NSLog(@"ClassOne");
 9     [super dealloc];
10 }
11 
12 
13 @end
classtwo.h
#import
<Foundation/Foundation.h> @interface ClassTwo : NSObject { @public int a; int b; } -(id)initClassTwo; @end
classtwo.m
1
#import "ClassTwo.h" 2 3 @implementation ClassTwo 4 -(id)initClassTwo 5 { 6 if(self=[super init]) 7 { 8 a=7; 9 b=4; 10 } 11 return self; 12 } 13 14 15 @end
classthree.h

1
#import "ClassOne.h" 2 3 @interface ClassThree : ClassOne 4 { 5 int c; 6 int d; 7 } 8 -(id)initClassThree; 9 -(void)print; 10 11 @end
classthree.m 

1
#import "ClassThree.h" 2 #import "ClassTwo.h" 3 4 @implementation ClassThree 5 -(id)initClassThree 6 { 7 if(self=[super init]) 8 { 9 c=4; 10 d=8; 11 p=[[ClassTwo alloc] initClassTwo]; 12 } 13 return self; 14 } 15 -(void)print 16 { 17 NSLog(@"%d\t%d\t%d\t%d",c,d,p->a,p->b); 18 } 19 -(void)dealloc 20 { 21 NSLog(@"ClassThree"); 22 23 [super dealloc]; 24 } 25 @end

 

 

 

 

posted @ 2014-01-14 21:34  恋~时光  阅读(134)  评论(0编辑  收藏  举报