OC中的结构体和枚举

关于OC中的结构体和枚举的使用,可以借鉴一下我写的代码,每个注释都是知识点

#import "ViewController.h"

//结构体
//ARC下禁止使用oc对象
//我由struct联想到enum
//使用结构体的系统类有 CGPoint, CGSize,CGRect ...
//结构体存储到数组和字典中需要转换成NSValue类型,同样的取出来的时候也要把NSValue转成相关的类型, 
//这类似于基本数据类型存储到数组和字典的时候需要转换成相应的NSNumber类型的数据情况.
struct student {
    float a;
    NSInteger age;
    char name;
};

//重定义 struct student -> Student
typedef struct student Student;

//声明 结构体 变量
Student student1;
Student student2;
//或者
struct student student3;
struct student student4;


//枚举
//下面两个是系统自带的enum, 一般推荐使用系统自带的的两个枚举这样便于代码的可读性,
//减少各种错误,让代码更加的规范
//一, NS_ENUM 二, NS_OPTIONS
//一, NS_ENUM
typedef NS_ENUM(NSInteger, ZLLEnum0)
{
    ZLLEnum0Error = 0,
    ZLLEnum0OK = 1,
    ZLLEnum0Flase = 1 << 0,  //c语言的左移运算
    ZLLEnum0Right = 1 << 2,  // 1左移2位,然后赋值给 ZLLEnum0Right
    ZLLEnum0Bottom = 1 << 3   //同理
};

//二, NS_OPTIONS
typedef NS_OPTIONS(NSInteger, ZLLEnum1)
{
    ZLLEnum1OK = 1,
    ZLLEnum1Error = 0,
    //ZLLEnum1False > 1
};

//自定义枚举
enum myfriend {
    Contacts_Stranger = 2,      //陌生人
    Contacts_NormalFriend,  //普通朋友
    Contacts_SpecialFriend  //好朋友
};
typedef enum myfriend Myfriend;


typedef enum {
    home_father, //编译器会为枚举分配一个编号,从0开始,每个枚举递增1,
                //如果指定某一个编号的值,则会从该枚举开始在该枚举的值上一次递增1.
    home_mather = 4,
    home_sister,
    home_wife
}Myhome;

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //struct
    //结构体赋值
    student1.a = 1.0;
    student1.age = 200;
    student1.name = 'f';
    student2 = student1;
    struct student student6 = {21.0, 180 , 'f'};
    
    //enum
    //枚举
    
    //定义一个枚举
    enum myfriend friend = Contacts_Stranger;
    //可以使用typedef简化枚举
    Myfriend friend1 = Contacts_NormalFriend;
    
    Myhome father = home_father;
    Myhome mather = home_mather;
    Myhome sister = home_sister;
    Myhome wife = home_wife;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

你可能感兴趣的:(OC中的结构体和枚举)