標籤:
特殊類型的封裝類:數組、結構體(OC內部的、自訂的)、指標
1 // 2 // main.m 3 // 05-NSValue 4 // 5 // Created by ma c on 15/8/17. 6 // Copyright (c) 2015年 bjsxt. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h>10 typedef struct11 {12 char *name;13 int age;14 char gender;15 }Student;16 17 int main(int argc, const char * argv[])18 {19 @autoreleasepool20 {21 //NSValue測試22 //1.指標23 int num = 10;24 int *p = #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中常用的結構體:NSRange\NSRect\NSSize\NSPoint39 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 }
Objective-C:NSValue類的常見用法