------- IOS培训、<a href="http://www.itheima.com" target="blank”>Mac、期待与您交流! —————
案例:
--Person.h--
#import <Foundation/Foundation.h>
#import "Card.h"
// @class仅仅是告诉编译器,Card是一个类
//@class Card;
@interface Person : NSObject
@property (nonatomic, retain) Card *card;
@end
--Person.m--
--Student.h--
#import "Person.h"
#import "Card.h"
@implementation Person
- (void)dealloc
{
NSLog(@"Person被销毁了");
[_card release];
[super dealloc];
}
@end
#import "Person.h"
@interface Student : Person
@property int no;
- (id)initWithNo:(int)no;
- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no;
@end
--Student.m--
@implementation Student
- (id)initWithNo:(int)no
{
if ( self = [super init] )
{
_no = no;
}
return self;
}
// 父类的属性交给父类方法去处理,子类方法处理子类自己的属性
- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
{
// 将name、age传递到父类方法中进行初始化
if ( self = [super initWithName:name andAge:age])
{
_no = no;
}
return self;
}
@end
--Main.m--
1.@class的作用:仅仅告诉编译器,某个名称是一个类
@class Person; // 仅仅告诉编译器,Person是一个类
2.开发中引用一个类的规范
1> 在.h文件中用@class来声明类
2> 在.m文件中用#import来包含类的所有东西
3.两端循环引用解决方案
1> 一端用retain
2> 一端用assign
#import <Foundation/Foundation.h>
#import "Card.h"
#import "Person.h"
int main()
{
// p - 1
Person *p = [[Person alloc] init];
// c - 1
Card *c = [[Card alloc] init];
// c - 2
p.card = c;
// p - 1
c.person = p;
// c - 1
[c release];
// p - 0 c - 0
[p release];
return 0;
}