pragma mark @class第二个应用场景
pragma mark 概念
/**
两个类相互引用,你拷贝我,我拷贝你,出现循环引用
*/
pragma mark 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#import "Person.h"
#pragma mark main函数
int main(int argc, const char * argv[])
{
Person *p = [Person new];
Dog *d = [Dog new];
p.dog = d;
[p release];
[d release];
return 0;
}
Person.h //人类
#import <Foundation/Foundation.h>
//#import "Dog.h"
/**
#import "Dog.h"
相当于
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Dog : NSObject
@property(nonatomic, retain)Person *owner;
@end
*/
@class Dog;
/**
总结: 如果两个类相互拷贝,例如A拷贝B,B拷贝A,这样会保存
如果解决:在.m中使用class,在.m中用import
因为如果.h中都没用#import, 例如A拷贝B,B拷贝A,会形成死循环
如果在.h@class,不会做任何拷贝操作,在.m中import 只会拷贝对应的文件,并不会形成死循环
*/
@interface Person : NSObject
@property(nonatomic, retain)Dog *dog;
@end
Person.m
#import "Person.h"
#import "Dog.h"
@implementation Person
- (void)dealloc
{
NSLog(@"%s",__func__);
[_dog release];
[super dealloc];
}
@end
Dog.h //狗类
#import <Foundation/Foundation.h>
//#import "Person.h"
@class Person;
// #import "Person.h"
// 相当于
//#import <Foundation/Foundation.h>
//#import "Person.h"
//@interface Dog : NSObject
//@property(nonatomic, retain)Person *owner;
//@end
//@interface Person : NSObject
//
//@property(nonatomic, retain)Dog *dog;
//
//@end
@interface Dog : NSObject
@property(nonatomic, retain)Person *owner;
@end
Dog.m
#import "Dog.h"
#import "Person.h"
@implementation Dog
- (void)dealloc
{
[_owner release];
NSLog(@"%s",__func__);
[super dealloc];
}
@end
网友评论