OC语言笔记(七):OC字符串Json、plist、NSNumber和NSValue、KVC

来源:互联网 发布:软考初级程序员答案 编辑:程序博客网 时间:2024/06/08 14:26

一、Json字符串

1、写一个Json字符串

    NSString *arrJsonStr =@"[\"pp\",\"qq\"]";//这个\后面的第一个字符只是一个字符,没有任何意义

    NSLog(@"%@",arrJsonStr);

    

    注意:Json字符串是这样的格式:@"",""中间任何内容不要加上@符号,字符串用""括起来,而不是@""括起来

    

2、解析Json字符串

    //这个是报错用的,当我们的代码执行是发生故障,我们就打印这个error,看看有什么问题

    NSError *error = nil;


   2.1Json字符串变成NSData

    NSData *arrData = [arrJsonStrdataUsingEncoding:NSUTF8StringEncoding];


    2.2解析这个Json字符串转成的Data,Json字符串是什么类型的,解的时候就用什么类型来接收

    NSArray *jsonArr = [NSJSONSerializationJSONObjectWithData:arrData options:NSJSONReadingMutableLeaveserror:&error];

    //第一个参数是data,就是那个json字符串转成的data。第二个参数是选项,设置解析方式。第三个是Error,出错的时候,打印这个error

    NSLog(@"%@",jsonArr);

    

   3、做一个字典类型的Json字符串//{\"name\":\"lily\",\"age\":\"18\"}

    NSString *dicJsonStr =@"{\"name\":\"lily\",\"age\":\"18\"}";

    NSLog(@"%@",dicJsonStr);

    

    NSDictionary *jsonDic = [NSJSONSerializationJSONObjectWithData:[dicJsonStr dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingMutableLeaveserror:&error];

    if(error)

    {

        NSLog(@"%@",error);

        return YES;

    }

    NSLog(@"%@",jsonDic);


二、plist文件

1、从plist文件中把数据读出来

    //找到包中文件(左侧文件列表中的文件)

    NSString *myFirstPlistFile = [[NSBundlemainBundle] pathForResource:@"MyFirstPlist"ofType:@"plist"];

    

    NSArray *plistArr1 = [NSArrayarrayWithContentsOfFile:myFirstPlistFile];//参数是一个plist文件的路径+文件名+扩展名

    NSLog(@"%@",plistArr1);

    

    //读出第二个plist文件

    NSDictionary *plistDic1 = [NSDictionarydictionaryWithContentsOfFile:[[NSBundlemainBundle] pathForResource:@"MySecondPlist"ofType:@"plist"]];

    NSLog(@"%@",plistDic1);x


2PList文件的查找步骤(参见:OCPList查找步骤截图)

2.1、在沙盒中找到所建文件,右击应用程序,选择“显示包内容”;

2.2、打开后,即可找到所创建的PList文件。


三、NSNumberNSValue


int age =10;

float weight =200.0;

//NSArray *ageArr = @[[NSString stringWithFormat:@"%d",age]];可以把数字变成字符串再存进数组


1、使用NSNumber将基本数据类型(int,float,double,char....)转变成NSNumber对象

    1.1、把基本类型变成NSNumber对象

    NSNumber *ageNum = [NSNumbernumberWithInt:age];//NSNumber的作用,就是把一个基本类型的变量转为对象,在这里,我们把age这个整形变成了一个NSNumber的对象

    

    NSNumber *weightNum = [NSNumbernumberWithFloat:weight];

    

    NSLog(@"%@,%@",ageNum,weightNum);

    

    NSLog(@"%d,%f",age,weight);

    

     1.2、把NSNumber对象变成基本类型

    

    int backAge = [ageNum intValue];

    

    float backWeight = [weightNum floatValue];

    

    NSLog(@"%d,,,%f",backAge,backWeight);

    

    NSString *str = @"1234";

    int strnumber = [str intValue];

    NSLog(@"%d",strnumber);

    

   2、基本类型转换成对象的两种方法

例子:34.2,请分别用NSStringNSNumber的方法,把这个数变成对象,再变回基本类型

    NSString *testStr = [NSStringstringWithFormat:@"%f",34.2];

    NSNumber *testNum = [NSNumbernumberWithFloat:34.2];

    

    float testStrFloat = [testStr floatValue];

    float testNumFloat = [testNum floatValue];

    

3、循环实例化人的对象(name自由组合,age随机数生成),并放入到可变数组中排序

    //要计算一个数组中10个人的岁数,按照年龄排序,并打印最后的年龄升序的姓名列表

    //循环实例化十个人,存进一个可变数组,实例化的时候,给这是个人的两个属性赋值

    NSArray *firstNameArr =@[@"",@"",@"",@"",@"",@"",@"",@""];

    NSArray *lastNameArr =@[@"",@"",@"",@"",@"",@"",@"",@""];

    

    NSMutableArray *peopleArr = [NSMutableArrayarrayWithCapacity:0];

    for(int i =0;i<10;i++)

    {

        OldPeople *people = [OldPeoplealloc];//循环十次,每次实例化一个老人对象,并未这个老人对象的姓名和年龄随机赋值

        people.name = [NSStringstringWithFormat:@"%@%@",firstNameArr[arc4random()%7],lastNameArr[arc4random()%7]];

        people.age = [NSStringstringWithFormat:@"%d",arc4random()%100];

        //[NSNumber numberWithInt:arc4random()%100];

        

        [peopleArr addObject:people];//把每次循环做好的老人存进数组

    }

    

    //排序

    for(int i =0;i<peopleArr.count-1;i++)//数组.count就是数组的长度

    {

        for(int j =0;j<peopleArr.count-1;j++)

        {

            OldPeople *temp = peopleArr[j];//数组里存的都是一个一个的老人对象,所以取出来的时候也是一个一个老人的对象

            OldPeople *tempNext = peopleArr[j+1];

            

            //把两个人的年龄字符串属性转为int类型

            int tempAge = [temp.ageintValue];

            int tempNextAge = [tempNext.ageintValue];

            

            if(tempAge > tempNextAge)

            {

                [peopleArr exchangeObjectAtIndex:jwithObjectAtIndex:j+1];

            }

        }

    }

    

    for(OldPeople *tempin peopleArr)

    {

        NSLog(@"姓名:%@,年龄:%@",temp.name,temp.age);

    }

    

    

   4、使用NSValue将结构体转变成对象

    NSRange range = NSMakeRange(3, 10);

    NSValue *rangeValue = [NSValuevalueWithRange:range];

    NSArray *rangeArr = @[rangeValue];

    //上面是把结构体变成对象

    //下面是吧对象变回结构体

    NSRange backRange = [rangeValue rangeValue];

    NSLog(@"%d,%d",backRange.location,backRange.length);


四、KVC赋值

1、.h文件中的写法(以People类为例)

#import <Foundation/Foundation.h>


@interface People : NSObject


@property(nonatomic)NSString *name;

@property(nonatomic)NSString *age;

@property(nonatomic)NSString *tel;

@property(nonatomic)NSString *address;



-(id)initWith:(NSDictionary*)dic;


-(void)setValue:(id)value forUndefinedKey:(NSString *)key;//请注意:这里要用UndefinedKey这个方法


-(NSString*)description;//这个方法是一个系统预置的,没有实现的,有一个NSString返回值的,可以在这里把所有属性的值拼成一个字符串一起返回用的


@end


2、.m文件中的写法(以People类为例)

#import "People.h"


@implementation People


-(id)initWith:(NSDictionary *)dic

{

    self = [superinit];

    if(self)

    {

        [selfsetValuesForKeysWithDictionary:dic];//kvc的赋值方式

        //会在字典中查找字典中的key与当前类的属性名是否一样,如果一样就会给对应的属性赋值

    }

    return self;

}


-(void)setValue:(id)value forUndefinedKey:(NSString *)key

{//防崩大法:可以检测出在AppDelegate.m文件中调用方法时key值的书写正确性

    NSLog(@"%@",key);

}


-(NSString*)description

{

    return [NSStringstringWithFormat:@"%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@",self.name,self.age,self.address,self.tel,self.email,self.surfaceColor,self.sex,self.height,self.hobby,self.weight,self.job,self.qq];

}


@end


3、AppDelegate.m文件中的写法(以People类为例)


People *first = [[Peoplealloc] initWith:@{@"name":@"pp",@"age":@"18",@"address":@"天丰利",@"tel":@"13333333333"}];

    NSLog(@"%@,%@,%@",first.name,first.age,first.address);

    

    //打印这个类对象的所有属性的值,和KVC没关系

    NSLog(@"%@",[firstdescription]);


0 0