iOS开发结构体如何存入数组中

电脑杂谈  发布时间:2019-12-22 08:01:03  来源:网络整理

结构体的数组指针_结构体数组_树体结构

1、常见结构体的储存

比较常用的结构体:CGPoint ,CGSize结构体数组,CGRect。。。。。。我们怎么存放到数组中呢?因为是结构体不是对象,不能添加到变量中,解决办法:把这种常用的结构装换成对象,让后放回去结构体数组,取下来在装换成结构体使用。我们想到了NSValue使用方式如下:

CGPoint point = CGPointMake(0, 0);

NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:0];

NSValue *value = [NSValue valueWithCGPoint:point];

[array addObject:value];

取出数组之后的对象的使用:

NSValue *tmpValue = array[0];

CGPoint tmpPoint = [tmpValue CGPointValue];

下面是一些常用的结构体使用方式是一样的

树体结构_结构体数组_结构体的数组指针

+ (NSValue *)valueWithCGPoint:(CGPoint)point;

+ (NSValue *)valueWithCGVector:(CGVector)vector;

+ (NSValue *)valueWithCGSize:(CGSize)size;

+ (NSValue *)valueWithCGRect:(CGRect)rect;

+ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform;

+ (NSValue *)valueWithUIEdgeInsets:(UIEdgeInsets)insets;

+ (NSValue *)valueWithUIOffset:(UIOffset)insets NS_AVAILABLE_IOS(5_0);

- (CGPoint)CGPointValue;

- (CGVector)CGVectorValue;

- (CGSize)CGSizeValue;

结构体数组_树体结构_结构体的数组指针

- (CGRect)CGRectValue;

- (CGAffineTransform)CGAffineTransformValue;

- (UIEdgeInsets)UIEdgeInsetsValue;

- (UIOffset)UIOffsetValue NS_AVAILABLE_IOS(5_0);

@end

2、自定义结构体的存储

同样是先转化NSValue对象再加入数组中,代码如下:

//自定义结构体

typedef struct Books

{

结构体的数组指针_树体结构_结构体数组

NSString *title;

NSString *author;

NSString *subject;

int book_id;

} book;

//初始化结构体数据

book book1 = {@"首页",@"作者",@"子类",1};

book book2 = {@"首页",@"作者",@"子类",2};

book book3 = {@"首页",@"作者",@"子类",3};

//存入数据

结构体数组_树体结构_结构体的数组指针

NSValue *customValue1 = [NSValue valueWithBytes:&book1 objCType:@encode(struct Books)];

NSValue *customValue2 = [NSValue valueWithBytes:&book2 objCType:@encode(struct Books)];

NSValue *customValue3 = [NSValue valueWithBytes:&book3 objCType:@encode(struct Books)];

NSMutableArray *books = [NSMutableArray arrayWithObjects:customValue1,customValue2,customValue3, nil];

//取出数据

[books enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

book value;

NSValue *customValue = obj;

[customValue getValue:&value];

NSLog(@"%d",value.book_id);

}];


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-134244-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      • 烟霏
        烟霏

        我们做出反应是有必要的

      热点图片
      拼命载入中...