结构体和类的区别-Objective-C基础

1 结构体 与类的相同点
都可以将多个数据封装为1个整体

struct Date{
int year;
int month;
int day;
}
@interface Date :NSObject
{
int year;
int month;
int day;
}
@end

2 结构体与类的不同点
1) 结构体只能封装数据 而类不仅可以封装数据 还可以封装行为。

2) 1结构体变量分配 在栈空间 (如果是1个局部变量的情况下
而对象分配在堆空间

沾的特点 空间相对较小 但是存储在栈中的数据访问的效率更高一些
堆的特点 空间相对较大, 但是存储在堆中的数据访问的效率相对要低
存储在栈中的数据访问效率高,存储在堆中的数据访问效率低

3)
赋值
结构体 Student
类 Perosn
Student s1 = {“jack”,19,GenderMale};
Student s2 = s1;

Person *p1 = [Person new];
Person *p2 = p1;

3 .应用场景

1) 如果表示的这个实体 不仅是由多个数据组成 ,这个是实体还有行为 ,不解释 只能使用类

2) 如果表示的实体没有行为 光有属性
a。 如果属性较少 只有几个 那么这个时候就定义为结构体,分配在沾 提高效率

b 如果属性较多 不要定义成结构体
因为这样结构体变量会在栈中占据很大1块空间,反而会影响效率
定义为类
枚举类型

main 方法代码

Author *a1 = [Author new];
[a1 setName:@“xxx斯基”];
[a1 setAge:68];
[a1 setGender:GenderMale];

Book *b1 = [Book new];
[b1 setName:@“钢铁是怎么练成的”];
[b1 setPublishDate:(Date){1998,12,12}];
[b1 setPublisherName:@“人民邮电出版社”];
[b1 setAuthor:a1];

Student *s1 = [Student new];
[s1 setName:@“小东”];
[s1 setAge:18];
[s1 setGender:GenderFemale];
[s1 setBook:b1];

typedef enum
{
GenderMale, //男
GenderFemale //女
} Gender;

Person : NSObject
{
NSString *_name;
int _age;
Gender _gender;

}
-(void)setName:(NSString *)name;
-(NSString *)name;
-(void)setGender:(Gender)gender;

-(Gender)gender;
-(void)setAge:(int)age;
-(int)age;

-(void)setName:(NSString *)name
{
_name=name;
}
-(NSString *)name
{return _name;
}
-(void)setGender:(Gender)gender{
_gender=gender;
}

-(Gender)gender{
return _gender;
}
-(void)setAge:(int)age{
_age=age;
}
-(int)age{
return _age;
}

Student : Person
{
NSString *_stuNumber;
Book *_book;

}
-(void)setBook:(Book *)book;
-(Book *)book;

-(void)setStuNumber:(NSString *)stuNumber;
-(NSString *)stuNumber;
-(void)setStuNumber:(NSString *)stuNumber{
_stuNumber = stuNumber;
}
-(NSString *)stuNumber{
return _stuNumber;
}

-(void)setBook:(Book *)book{
_book=book;
}
-(Book *)book{
return _book;
}

typedef struct{
int year;
int month;
int day;
} Date;

Book : NSObject{
NSString *_name;
NSString _publisherName;
Author *_author;
Date _publishDate;
}

-(void)setPublishDate:(Date)publishDate;
-(Date)publishDate;

-(void)setName:(NSString *)name;
-(NSString *)name;

-(void)setPublisherName:(NSString *)publisherName;
-(NSString *)publisherName;
-(void)setAuthor:(Author *)author;
-(Author *)author;

-(void)setPublishDate:(Date)publishDate
{
_publishDate= publishDate;
}
-(Date)publishDate{
return _publishDate;
}
-(void)setName:(NSString *)name{
_name=name;
}
-(NSString *)name{
return _name;
}

-(void)setPublisherName:(NSString *)publisherName{
_pushlisherName = publisherName;
}
-(NSString *)publisherName{
return _publisherName;
}
-(void)setAuthor:(Author *)author{
_author = author;
}
-(Author *)author{
return _author;
}

Author : Person
{

}
-(void) writeBook;

-(void) writeBook{
NSLog(@“一本旷世著作就这么诞生了”);
}

上一篇:Objective C 各种数据类型转换笔记大全


下一篇:iOS基础 - Objective-C编码规范