• Objective-C:NSValue类的常见用法


    特殊类型的包装类:数组、结构体(OC内部的、自定义的)、指针

     1 //
     2 //  main.m
     3 //  05-NSValue
     4 //
     5 //  Created by ma c on 15/8/17.
     6 //  Copyright (c) 2015年. All rights reserved.
     7 //
     8 
     9 #import <Foundation/Foundation.h>
    10 typedef struct
    11 {
    12     char *name;
    13     int age;
    14     char gender;
    15 }Student;
    16 
    17 int main(int argc, const char * argv[])
    18 {
    19     @autoreleasepool
    20     {
    21         //NSValue测试
    22         //1.指针
    23         int num = 10;
    24         int *p = &num;
    25         NSValue *value1 = [NSValue valueWithPointer:p];
    26         int *p2 = (int*)[value1 pointerValue];
    27         NSLog(@"num = %d",*(p2));
    28         
    29         //2.数组
    30         int arr[5] = {1,2,3,4,5};
    31         NSValue *value2 = [NSValue valueWithPointer:arr];
    32         int *p3 = (int*)[value2 pointerValue];
    33         for(int i=0; i<5; i++)
    34         {
    35             NSLog(@"%d",p3[i]);
    36         }
    37         
    38         //3.Foundation中常用的结构体:NSRangeNSRectNSSizeNSPoint
    39         NSRange range = NSMakeRange(0, 5);
    40         NSValue *value3 = [NSValue valueWithRange:range];
    41         NSRange range2 = [value3 rangeValue];
    42         NSLog(@"%@",NSStringFromRange(range2));
    43         
    44         NSRect rect = NSMakeRect(0, 0, 100, 100);
    45         NSValue *value4 = [NSValue valueWithRect:rect];
    46         NSRect rect2 = [value4 rectValue];
    47         
    48         NSLog(@"%@",NSStringFromRect(rect2));
    49         
    50         
    51         //4.自定义的结构体
    52         Student stu = {"Tom",20,'M'};
    53         NSValue *value5 = [NSValue valueWithBytes:&stu objCType:@encode(Student)];
    54         NSLog(@"%s",@encode(Student));//输出结构体类型
    55         
    56         Student stu2;
    57         [value5 getValue:&stu2];
    58         NSLog(@"name = %s,age = %i,gender = %c",stu2.name,stu2.age,stu2.gender);
    59     }
    60     return 0;
    61 }
  • 相关阅读:
    VC++对话框笔记
    STL中用erase()方法遍历删除元素
    VC++中不小心选错工程类型的解决办法
    directX中常用的数学计算
    VC++中string、char* 转换为LPCSTR
    判断空间上点是否在直线上
    vc6.0插件
    VC++常用定义(如SAFE_DELETE等)
    关于控件的AutoSize属性影响界面布局的问题解决
    C#判断日期是否正确(1900~今年,月份,天数)
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/4737485.html
Copyright © 2020-2023  润新知