1.NSString *greeting = [NSString
stringWithUTF8String:"hello"];
NSString *greeting =
@"hello";
2.NSArray *array = [NSArray arrayWithObjects:a,b,c,
nil];
NSArray *array =
@[a,b,c];
3.[array
objectAtIndex:1];
array[1];
4.di = [NSDictionary dictionaryWithObjects:@[1,2,3]
forKeys:@[k1,k2,k3],
nil];
di =
@{k1:1,k2:2,k3:3}
@[1,2,3]是一个数组,@[k1,k2,k3]也是一个数组
5.[NSDictionary dictionaryWithObjectsAndKeys:v1,k1,v2,k2
nil];
@{k1:v1,k2:v2};
6.[dictionary valueForKey:k];
dictionary[k];
语法简化 [ NSNumber ]
1.NSNumber *value;
value = @12345;
value = @123.45f;
value = @123.45;
value = @YES;
例子:
int a = 10;
NSNumber *a1
= [NSNumber numberWithChar:a];
NSNumber *a1
[email protected];
2.[NSArray ]
NSArray *array;
array = @[]; //空数组
array = @[ a ]; //一个对象的数组
array = @[ a, b, c ]; //多个对象的数组
3.[NSDictionary]
NSDictionary *dict;
dict = @{}; //空字典
dict = @{ k1 : o1 }; //包含一个键值对的字典
dict = @{ k1 : o1, k2 : o2, k3 : o3 }; //包含多个键值对的字典
注:对可变的容器,可以用:
NSMutableArray *mutablePlanets = [@[
@"Mercury", @"Venus", @"Earth",
@"Mars", @"Jupiter", @"Saturn",
@"Uranus", @"Neptune"
] mutableCopy];
NSArray
NSArray *array = @[ a, b, c ];
id obj = array[i]; //通过下标方式获取数组对象,替换原有写法:[array objectAtIndex:i];
array[i] = newObj; //也可以直接为数组对象赋值。替换原有写法:[array replaceObjectAtIndex:i withObject:newObj];
NSDictionary
NSDictionary *dict = @{ k1 : o1, k2 : o2, k3 : o3 };
id obj = dict[k2]; //获取o2对象,替换原有写法:[dic objectForKey:k2];
dic[k2] = newObj; //重新为键为k2的对象赋值,替换原有写法:[dic setObject:newObj forKey:k2]
4.语法简化
4.1 NSNumber
NSNumber *value;
value = @12345;
value = @123.45f;
value = @123.45;
value = @YES;
4.2 NSArray
NSArray *array;
array = @[];
array = @[ a ];
array = @[ a, b, c ];
4.3 NSDictionary
NSDictionary *dict;
dict = @{}; //空字典
dict = @{ k1 : o1 }; //包含一个键值对的字典
dict = @{ k1 : o1, k2 : o2, k3 : o3 }; //包含多个键值对的字典
- 4.3 NSDictionary
- NSDictionary *dict;
- dict = @{}; //空字典
- dict = @{ k1 : o1 }; //包含一个键值对的字典
- dict = @{ k1 : o1, k2 : o2, k3 : o3 }; //包含多个键值对的字典
- 注:对可变的容器,可以用:
- NSMutableArray *mutablePlanets = [@[
- @"Mercury", @"Venus", @"Earth",
- @"Mars", @"Jupiter", @"Saturn",
- @"Uranus", @"Neptune"
- ] mutableCopy];
- 5.对象下标
- 可以通过下标方式存取数组和字典的数据,类似C语言结构
- 5.1 NSArray
- NSArray *array = @[ a, b, c ];
- id obj = array[i]; //通过下标方式获取数组对象,替换原有写法:array objectAtIndex:i];
- array[i] = newObj; //也可以直接为数组对象赋值。替换原有写法:[array replaceObjectAtIndex:i withObject:newObj];
- 5.2 NSDictionary
- NSDictionary *dict = @{ k1 : o1, k2 : o2, k3 : o3 };
- id obj = dict[k2]; //获取o2对象,替换原有写法:[dic objectForKey:k2];
- dic[k2] = newObj; //重新为键为k2的对象赋值,替换原有写法:[dic setObject:newObj forKey:k2]
- 6.小结
- @# nsnumbers
- @{} dictionaries
- @“” strings
- @[] arrays
- @() expressions
@# nsnumbers
@{} dictionaries
@“” strings
@[] arrays
@() expressions
- 4.3 NSDictionary
- NSDictionary *dict;
- dict = @{}; //空字典
- dict = @{ k1 : o1 }; //包含一个键值对的字典
- dict = @{ k1 : o1, k2 : o2, k3 : o3 }; //包含多个键值对的字典