字面量语法 第一、字面数值 复杂方法: NSNumber *someNumber=[NSNumber numberWithDouble:3.4]; NSLog(@”the value is %@”,someNumber); 替代方法: NSNumber *a=@21.3; NSNumber *b=@32; NSLog(@”the value is %@”,a);
NSLog(@”the value is %@”,b);
第二、字面数组 复杂方法: NSArray *arr=[NSArray arrayWithObjects:@”hello”,@”richard”,@”yang”, nil]; NSLog(@”the first object is %@”,[arr objectAtIndex:0]); 替代方法 NSArray *arr1=@[@”hello”,@”richard”,@”yang”]; NSLog(@”the first object is %@”,arr1[1]); 注意事项:
用字面量语法创建数组时,若有元素对象为nil,则会抛出异常,而用arrayWithObjects创建,nil前面的数据可以正确创建 第三、字面量字典 复杂方法: NSDictionary *personDic=[NSDictionary dictionaryWithObjectsAndKeys:@”richard”,@”name”,@”001”,@”num”, nil]; NSLog(@”name is %@”,[personDic valueForKey:@”name 替代方法: NSDictionary *personDic=@{@”name”:@”richard”,@”num”:@”001”};
NSLog(@”the name is %@”,personDic[@”name”]);
第四、常见可变对象 NSMutableArray *arr1=[@[@”hello”,@”richard”,@”yang”] mutableCopy];
使用字面量语法创建的可变对象时需要加上mutaleCopy
第五、使用字面量语法修改值 NSMutableArray *arr1=[@[@”hello”,@”richard”,@”yang”] mutableCopy]; NSLog(@”the first value is %@”,arr1[0]); arr1[0]=@”andy”;
NSLog(@”the first value is %@”,arr1[0]);