oc温习七:结构体与枚举

结构体和枚举都是一种存储复杂的数据。结构体是用户自定义的一种类型,不同类型的集合。

1.结构体的创建及使用

  • 定义结构体类型
struct MyDate {
    int year;
    int month;
    int day;
};
typedef struct MyDate MyDate;   //如果不加这句话,每次调用这个MyDate的数据结构时,都需要加上struct 这个类型
  •  结构体的调用
//在需要的地方调用即可
 MyDate date = {2017, 7, 21};
 NSLog(@"-----year=%d, month=%d, day=%d-----", date.year, date.month, date.day);
  •  结构体数据组装的方法

因为在使用CGSize的时候,size的有个数据组装的方法:CGMakeSize();所以如果也要自己生成这样一个方法时,如下步骤:

--》1.导入头文件  #include <CoreGraphics/CGBase.h>
--》2.CG_INLINE ***结构体(例如:CG_INLINE MyDate)
--》3.自定义组装数据的方法名以及类型,如下:
CG_INLINE MyDate
ZWYLMakeDate(int year, int month, int day) {
    struct MyDate date; date.year = year; date.month = month, date.day = day;
    return date;
}
  •  组装数据方法的使用
MyDate date = ZWYLMakeDate(2017, 7, 21);
NSLog(@"-----year=%d, month=%d, day=%d-----", date.year, date.month, date.day);
  •  oc中常见的结构体有:NSPoint 和 CGPoint; NSSize 和 CGSize;  NSRect 和 CGRect

2.枚举类型的使用

先推荐两篇文章吧,说的确实挺清楚与深入的。

http://blog.csdn.net/daleiwang/article/details/50581872

http://www.jianshu.com/p/97e582fe89f3

这里只举个例子吧:

  • 单个枚举类型的创建
typedef  NS_ENUM(NSInteger, testSingle) {
    testSingleOne = 0,
    testSingleTwo = 1,
    testSingleLitterWay = 2
};
  •  单个枚举类型的使用
/** 单个枚举值的用法 */
- (void)logSingleType:(testSingle)singleType {
    NSLog(@"-----%ld %ld %ld-----", singleType & testSingleOne, singleType & testSingleTwo, singleType & testSingleLitterWay);
    
    if (singleType == 0) {
        NSLog(@"-----0-----");
    }
    
    if (singleType == 1 ) {
        NSLog(@"-----1-----");
    }
    
    if (singleType == 2 ) {
        NSLog(@"-----2-----");
    }
    
    
}

//-----调用:例如在viewDidLoad中调用
[self logSingleType:testSingleOne];
  • 多个枚举类型的创建
typedef NS_OPTIONS(NSInteger, testNSEum) {
    testNSEumLeft = 1 << 0, //==1
    testNSEumRight = 1 << 1, //==2
    testNSEumTop = 1 << 2,  //==4
    testNSEumBottom = 1 << 3,  //==8
};
  •  多个枚举类型的使用
/** 多个枚举值组合后的解决方法 */
- (void)logMessage:(testNSEum)type {
    NSLog(@"-----%ld %ld %ld %ld-----", type & testNSEumTop , type & testNSEumBottom, type & testNSEumRight, type & testNSEumLeft);
    if (type & testNSEumTop ) {
        NSLog(@"-----type=testNSEumTop-----");
    }
    
    if (type & testNSEumBottom) {
        NSLog(@"-----type=testNSEumBottom-----");
    }
    
    if (type & testNSEumRight) {
        NSLog(@"-----type=testNSEumRight-----");
    }
    
    if (type & testNSEumLeft) {
        NSLog(@"-----type=testNSEumLeft-----");
        
    }
    
}

// 调用--例如在ViewDidLoad调用
[self logMessage:testNSEumLeft | testNSEumBottom | testNSEumRight];

3.结构体与类的区别:

a.    结构体只能封装数据,而类还可以封装行为

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

                          i.        栈的特点:空间相对较小,但是存储在栈中得数据访问的效率稍高一些

                          ii.        堆的特点:空间的相对较大,但是存储在堆中的数据,效率低一些

                         iii.        存储在栈中得数据访问效率高, 存储在堆中得数据效率低

 

原文地址:https://www.cnblogs.com/lyz0925/p/7218938.html