NSValue封装自定义的结构体

本文介绍如何通过Objective-C中的NSValue类将自定义结构体类型封装为对象,并提供了具体的实例代码,包括创建结构体、封装结构体为NSValue对象以及从NSValue对象中取出结构体的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typedef struct {
    int i;
    float f;
} MyIntegerFloatStruct;
you can create an NSValue instance by providing a pointer to the structure as well as an encoded Objective-C type. The @encode() compiler directive is used to create the correct Objective-C type, like this:

    struct MyIntegerFloatStruct aStruct;
    aStruct.i = 42;
    aStruct.f = 3.14;
 
    NSValue *structValue = [NSValue value:&aStruct
                             withObjCType:@encode(MyIntegerFloatStruct)];

The standard C reference operator (&) is used to provide the address of aStruct for the value parameter.



typedef  struct{  //自定义一个结构体
    int age;
    int number;
}Student;

NSValue *stu=[NSValue valueWithBytes:&stu objCtype :@encode(Student)];//把结构体封装成一个对象


Student  value2;//定义一个结构体变量来接受从NSValue得到的结构体


[stu getValue:&value2];//把 stu对象中的结构体取出来


int a=value2.age;  //取得结构体中的字段


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值