[BS-02] iOS数组、字典、NSNumber 新写法—— @[]、@{}

IOS数组、字典、NSNumber 新写法—— @[]、@{}

 
//标准写法
NSNumber * number = [NSNumber numberWithInt:];
NSArray * array = [NSArray arrayWithObjects:@"one", @"two", nil];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; //快捷写法
NSNumber * number = @;
NSArray * array = @[@"one", @"two"];
NSDictionary * dict = @{@"key1":@"value1", @"key2":@"value2"}; NSMutableArray *m_array = [@[] mutableCopy];
NSMutableDictionary *m_dict = [@{} mutableCopy];
WWDC2012大会上介绍了大量Objective-C的新特性,能够帮助iOS程序员更加高效地编写代码。在XCode4.4版本中可以使用以下特性:

一.
Object Literals这个是我认为最赞的一个改进。Object Literals允许你方便地定义数字、数组和字典对象。这个功能类似于java5提供的auto boxing功能。这虽然是一个语法糖,但我认为对提高写代码效率帮助很大。让我们先来看看以前定义数字、数组和字典对象的方法: NSNumber * number = [NSNumber numberWithInt:];
NSArray * array = [NSArray arrayWithObjects:@"one", @"two", nil];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; 是不是很恶心?现在以上代码可以简化成以下形式,注意到没有,不用再在参数的最后加恶心的nil了,字典的key和value也不再是倒着先写value,再写key了:
NSNumber * number = @;
NSArray * array = @[@"one", @"two"];
NSDictionary * dict = @{@"key1":@"value1", @"key2":@"value2"}; 更多的示例如下: // 整数
NSNumber *fortyTwo = @; // 等价于 [NSNumber numberWithInt:42]
NSNumber *fortyTwoUnsigned = @42U; // 等价于 [NSNumber numberWithUnsignedInt:42U]
NSNumber *fortyTwoLong = @42L; // 等价于 [NSNumber numberWithLong:42L]
NSNumber *fortyTwoLongLong = @42LL; // 等价于 [NSNumber numberWithLongLong:42LL] // 浮点数
NSNumber *piFloat = @3.141592654F; // 等价于 [NSNumber numberWithFloat:3.141592654F]
NSNumber *piDouble = @3.1415926535; // 等价于 [NSNumber numberWithDouble:3.1415926535] // 布尔值
NSNumber *yesNumber = @YES; // 等价于 [NSNumber numberWithBool:YES]
NSNumber *noNumber = @NO; // 等价于 [NSNumber numberWithBool:NO] // 空数组
NSArray * array = @[]; // 等价于 [NSArray array]
// 空的字典
NSDictionary * dict = @{}; // 等价于 [NSDictionary dictionary] 怎么样?是不是简单多了?而且,为了方便你的旧代码迁移到新的写法,xcode专门还提供了转换工具,在xcode4.4中,选择 Edit -> Refactor -> Convert to Modern Objective-C Syntax即可。 二.
在XCode4.5中实现了一个很体贴的语法,它允许你使用中括号[]来代替原本的方法来获取get和设置set数组/字典元素。 简单来说,以前的 [array objectAtIndex:idx] 和 [array replaceObjectAtIndex:idx withObject:obj],可以直接写作 array[idx] 和 array[idx] = obj了。其实这个特性在很多高级语言中都实现了,只是Objective-C生于80年代,一直没改进这个。 使用【】访问数组、字典,使用@()作为计算表达式
NSArray * array = @[ @"", @"", @""];
for (int i = ; i < ; ++i) {
NSLog(@"array[i] = %@", array[i]);
} NSMutableDictionary * dict =[@{ @: @"value1",
@: @"value2",
@: @"value3" } mutableCopy];
for (int i = ; i < ; ++i) {
NSLog(@"dict[%d] = %@", i, dict[@(i+)]); //@()是计算表达式
dict[@(i+)] = [NSString stringWithFormat:@"new %@", dict[@(i+)]];
} [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"dict[%@] = %@", key, dict[key]);
}]; 使用【】对可变数组和可变字典设值:
NSMutableArray *arrayM = [NSMutableArray array];
//NSMutableArray * arrayM = @[ @"111" mutableCopy];//从不可变数组创建可变数组
array[0] = @"123";
array[1] = @"456";
NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
dictM[@"1"] = @"abc";
dictM[@"2"] = @"xyz";

三、遍历元素

你是如何遍历数组的元素的?通常我们有2种做法,一种是用 for in,另一种是用一个变量来循环数组下标。如下:
1    NSArray * array = @[@"123",@"abc",@"xyz"];
2    for (NSString * str in array) {
3       // ...
4    }
5    for (int i = 0; i < array.count; ++i) {
6        NSString * str = [array objectAtIndex:i];
7        ...
8    } 如果是字典,遍历的代码就要稍微复杂一点了:
1    NSDictionary * dict = @{@"1":@"abc",@"2":@"xyz"};
2    NSArray * keys = [dict allKeys];
3    for (NSString * key in keys) {
4        NSString * value = [dict objectForKey:key];
5    }
现在,xcode对于iOS4.0以上的系统,支持用block来遍历元素了。用block来遍历字典可以简化代码的编写,建议大家都使用上这个新特性。
1 [array enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL *stop) {

3 }]; 4 
5 [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

7 }];
//  ios 字符串 数组 字典 常用方法

/*
NSString
*/
//一、NSString
/----------------创建字符串的方法----------------/ //1、创建常量字符串。
NSString *astring = @"This is a String!"; //2、创建空字符串,给予赋值。 NSString *astring = [[NSString alloc] init];
astring = @"This is a String!";
[astring release];
NSLog(@"astring:%@",astring); //3、在以上方法中,提升速度:initWithString方法 NSString *astring = [[NSString alloc] initWithString:@"This is a String!"];
NSLog(@"astring:%@",astring);
[astring release]; //4、用标准c创建字符串:initWithCString方法 char Cstring = "This is a String!";
NSString astring = [[NSString alloc] initWithCString:Cstring];
NSLog(@"astring:%@",astring);
[astring release]; //5、创建格式化字符串:占位符(由一个%加一个字符组成) int i = ;
int j = ;
NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%d.This is %i string!",i,j]];
NSLog(@"astring:%@",astring);
[astring release]; //6、创建临时字符串 NSString *astring;
astring = [NSString stringWithCString:"This is a temporary string"];
NSLog(@"astring:%@",astring); /----------------从文件读取字符串:initWithContentsOfFile方法----------------/ NSString path = @"astring.text";
NSString astring = [[NSString alloc] initWithContentsOfFile:path];
NSLog(@"astring:%@",astring);
[astring release]; /----------------写字符串到文件:writeToFile方法----------------/ NSString astring = [[NSString alloc] initWithString:@"This is a String!"];
NSLog(@"astring:%@",astring);
NSString path = @"astring.text";
[astring writeToFile: path atomically: YES];
[astring release]; /----------------比较两个字符串----------------/ //用C比较:strcmp函数 char string1[] = "string!";
char string2[] = "string!";
if(strcmp(string1, string2) = = )
{
NSLog(@"");
} //isEqualToString方法
NSString astring01 = @"This is a String!";
NSString astring02 = @"This is a String!";
BOOL result = [astring01 isEqualToString:astring02];
NSLog(@"result:%d",result); //compare方法(comparer返回的三种值)
NSString astring01 = @"This is a String!";
NSString astring02 = @"This is a String!";
BOOL result = [astring01 compare:astring02] = = NSOrderedSame;
NSLog(@"result:%d",result);
//NSOrderedSame判断两者内容是否相同 NSString astring01 = @"This is a String!";
NSString astring02 = @"this is a String!";
BOOL result = [astring01 compare:astring02] = = NSOrderedAscending;
NSLog(@"result:%d",result);
//NSOrderedAscending判断两对象值的大小(按字母顺序进行比较,astring02大于astring01为真) NSString astring01 = @"this is a String!";
NSString astring02 = @"This is a String!";
BOOL result = [astring01 compare:astring02] = = NSOrderedDescending;
NSLog(@"result:%d",result);
//NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真) //不考虑大小写比较字符串1
NSString astring01 = @"this is a String!";
NSString astring02 = @"This is a String!";
BOOL result = [astring01 caseInsensitiveCompare:astring02] = = NSOrderedSame;
NSLog(@"result:%d",result);
//NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真) //不考虑大小写比较字符串2
NSString astring01 = @"this is a String!";
NSString astring02 = @"This is a String!";
BOOL result = [astring01 compare:astring02
options:NSCaseInsensitiveSearch | NSNumericSearch] = = NSOrderedSame;
NSLog(@"result:%d",result); //NSCaseInsensitiveSearch:不区分大小写比较 NSLiteralSearch:进行完全比较,区分大小写 NSNumericSearch:比较字符串的字符个数,而不是字符值。 /----------------改变字符串的大小写----------------/ NSString string1 = @"A String";
NSString string2 = @"String";
NSLog(@"string1:%@",[string1 uppercaseString]);//大写
NSLog(@"string2:%@",[string2 lowercaseString]);//小写
NSLog(@"string2:%@",[string2 capitalizedString]);//首字母大小 /----------------在串中搜索子串----------------/ NSString string1 = @"This is a string";
NSString string2 = @"string";
NSRange range = [string1 rangeOfString:string2];
int location = range.location;
int leight = range.length;
NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"Location:%i,Leight:%i",location,leight]];
NSLog(@"astring:%@",astring);
[astring release]; /----------------抽取子串 ----------------/ //-substringToIndex: 从字符串的开头一直截取到指定的位置,但不包括该位置的字符
NSString string1 = @"This is a string";
NSString string2 = [string1 substringToIndex:];
NSLog(@"string2:%@",string2); //-substringFromIndex: 以指定位置开始(包括指定位置的字符),并包括之后的全部字符
NSString string1 = @"This is a string";
NSString string2 = [string1 substringFromIndex:];
NSLog(@"string2:%@",string2); //-substringWithRange: //按照所给出的位置,长度,任意地从字符串中截取子串
NSString string1 = @"This is a string";
NSString string2 = [string1 substringWithRange:NSMakeRange(, )];
NSLog(@"string2:%@",string2); //扩展路径 NSString Path = @"~/NSData.txt";
NSString absolutePath = [Path stringByExpandingTildeInPath];
NSLog(@"absolutePath:%@",absolutePath);
NSLog(@"Path:%@",[absolutePath stringByAbbreviatingWithTildeInPath]); //文件扩展名
NSString *Path = @"~/NSData.txt";
NSLog(@"Extension:%@",[Path pathExtension]); /*
NSMutableString
*/ /---------------给字符串分配容量----------------/
//stringWithCapacity:
NSMutableString *String;
String = [NSMutableString stringWithCapacity:]; /---------------在已有字符串后面添加字符----------------/ //appendString: and appendFormat: NSMutableString String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
//[String1 appendString:@", I will be adding some character"];
[String1 appendFormat:[NSString stringWithFormat:@", I will be adding some character"]];
NSLog(@"String1:%@",String1); / /--------在已有字符串中按照所给出范围和长度删除字符------/
/
//deleteCharactersInRange:
NSMutableString String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
[String1 deleteCharactersInRange:NSMakeRange(, )];
NSLog(@"String1:%@",String1); /--------在已有字符串后面在所指定的位置中插入给出的字符串------/ //-insertString: atIndex:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
[String1 insertString:@"Hi! " atIndex:];
NSLog(@"String1:%@",String1); /--------将已有的空符串换成其它的字符串------/ //-setString:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
[String1 setString:@"Hello Word!"];
NSLog(@"String1:%@",String1); /--------按照所给出的范围,和字符串替换的原有的字符------/ //-setString:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
[String1 replaceCharactersInRange:NSMakeRange(, ) withString:@"That"];
NSLog(@"String1:%@",String1); /-------------判断字符串内是否还包含别的字符串(前缀,后缀)-------------/
//01:检查字符串是否以另一个字符串开头- (BOOL) hasPrefix: (NSString ) aString;
NSString String1 = @"NSStringInformation.txt";
[String1 hasPrefix:@"NSString"] = = ? NSLog(@"YES") : NSLog(@"NO");
[String1 hasSuffix:@".txt"] = = ? NSLog(@"YES") : NSLog(@"NO"); //02:查找字符串某处是否包含其它字符串 - (NSRange) rangeOfString: (NSString *) aString,这一点前面在串中搜索子串用到过; /*
NSArray
*/ /---------------------------创建数组------------------------------/
//NSArray *array = [[NSArray alloc] initWithObjects:
@"One",@"Two",@"Three",@"Four",nil]; self.dataArray = array;
[array release]; //- (unsigned) Count;数组所包含对象个数;
NSLog(@"self.dataArray cound:%d",[self.dataArray count]); //- (id) objectAtIndex: (unsigned int) index;获取指定索引处的对象;
NSLog(@"self.dataArray cound 2:%@",[self.dataArray objectAtIndex:]); /--------------------------从一个数组拷贝数据到另一数组(可变数级)----------------------------/ //arrayWithArray:
//NSArray array1 = [[NSArray alloc] init];
NSMutableArray MutableArray = [[NSMutableArray alloc] init];
NSArray *array = [NSArray arrayWithObjects:
@"a",@"b",@"c",nil];
NSLog(@"array:%@",array);
MutableArray = [NSMutableArray arrayWithArray:array];
NSLog(@"MutableArray:%@",MutableArray); array1 = [NSArray arrayWithArray:array];
NSLog(@"array1:%@",array1); //Copy //id obj;
NSMutableArray newArray = [[NSMutableArray alloc] init];
NSArray oldArray = [NSArray arrayWithObjects:
@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil]; NSLog(@"oldArray:%@",oldArray);
for(int i = ; i < [oldArray count]; i++)
{
obj = [[oldArray objectAtIndex:i] copy];
[newArray addObject: obj];
}
//
NSLog(@"newArray:%@", newArray);
[newArray release]; //快速枚举 //NSMutableArray newArray = [[NSMutableArray alloc] init];
NSArray oldArray = [NSArray arrayWithObjects:
@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];
NSLog(@"oldArray:%@",oldArray); for(id obj in oldArray)
{
[newArray addObject: obj];
}
//
NSLog(@"newArray:%@", newArray);
[newArray release]; //Deep copy //NSMutableArray newArray = [[NSMutableArray alloc] init];
NSArray oldArray = [NSArray arrayWithObjects:
@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];
NSLog(@"oldArray:%@",oldArray);
newArray = (NSMutableArray*)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFPropertyListRef)oldArray, kCFPropertyListMutableContainers);
NSLog(@"newArray:%@", newArray);
[newArray release]; //Copy and sort //NSMutableArray newArray = [[NSMutableArray alloc] init];
NSArray oldArray = [NSArray arrayWithObjects:
@"b",@"a",@"e",@"d",@"c",@"f",@"h",@"g",nil];
NSLog(@"oldArray:%@",oldArray);
NSEnumerator *enumerator;
enumerator = [oldArray objectEnumerator];
id obj;
while(obj = [enumerator nextObject])
{
[newArray addObject: obj];
}
[newArray sortUsingSelector:@selector(compare:)];
NSLog(@"newArray:%@", newArray);
[newArray release]; /---------------------------切分数组------------------------------/ //从字符串分割到数组- componentsSeparatedByString:
NSString string = [[NSString alloc] initWithString:@"One,Two,Three,Four"];
NSLog(@"string:%@",string);
NSArray array = [string componentsSeparatedByString:@","];
NSLog(@"array:%@",array);
[string release]; //从数组合并元素到字符串- componentsJoinedByString:
NSArray array = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",nil];
NSString string = [array componentsJoinedByString:@","];
NSLog(@"string:%@",string); /*
NSMutableArray
*/
/---------------给数组分配容量----------------/
//NSArray *array;
array = [NSMutableArray arrayWithCapacity:]; /--------------在数组末尾添加对象----------------/
//- (void) addObject: (id) anObject;
//NSMutableArray *array = [NSMutableArray arrayWithObjects:
@"One",@"Two",@"Three",nil];
[array addObject:@"Four"];
NSLog(@"array:%@",array); /--------------删除数组中指定索引处对象----------------/
//-(void) removeObjectAtIndex: (unsigned) index;
//NSMutableArray *array = [NSMutableArray arrayWithObjects:
@"One",@"Two",@"Three",nil];
[array removeObjectAtIndex:];
NSLog(@"array:%@",array); /-------------数组枚举---------------/
//- (NSEnumerator )objectEnumerator;从前向后
//NSMutableArray array = [NSMutableArray arrayWithObjects:
@"One",@"Two",@"Three",nil];
NSEnumerator *enumerator;
enumerator = [array objectEnumerator]; id thingie;
while (thingie = [enumerator nextObject]) {
NSLog(@"thingie:%@",thingie);
} //- (NSEnumerator )reverseObjectEnumerator;从后向前
//NSMutableArray array = [NSMutableArray arrayWithObjects:
@"One",@"Two",@"Three",nil];
NSEnumerator *enumerator;
enumerator = [array reverseObjectEnumerator]; id object;
while (object = [enumerator nextObject]) {
NSLog(@"object:%@",object);
} //快速枚举
//NSMutableArray array = [NSMutableArray arrayWithObjects:
@"One",@"Two",@"Three",nil];
for(NSString string in array)
{
NSLog(@"string:%@",string);
} /*
NSDictionary
*/ /------------------------------------创建字典------------------------------------/
//- (id) initWithObjectsAndKeys; //NSDictionary dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"One",@"1",@"Two",@"2",@"Three",@"3",nil];
NSString string = [dictionary objectForKey:@"One"];
NSLog(@"string:%@",string);
NSLog(@"dictionary:%@",dictionary);
[dictionary release]; /*
NSMutableDictionary
*/ /------------------------------------创建可变字典------------------------------------/
//创建
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; //添加字典
[dictionary setObject:@"One" forKey:@""];
[dictionary setObject:@"Two" forKey:@""];
[dictionary setObject:@"Three" forKey:@""];
[dictionary setObject:@"Four" forKey:@""];
NSLog(@"dictionary:%@",dictionary); //删除指定的字典
[dictionary removeObjectForKey:@""];
NSLog(@"dictionary:%@",dictionary); /*
NSValue(对任何对象进行包装)
*/ /--------------------------------将NSRect放入NSArray中------------------------------------/
//将NSRect放入NSArray中
NSMutableArray array = [[NSMutableArray alloc] init];
NSValue value;
CGRect rect = CGRectMake(, , , );
value = [NSValue valueWithBytes:&rect objCType:@encode(CGRect)];
[array addObject:value];
NSLog(@"array:%@",array); //从Array中提取
value = [array objectAtIndex:];
[value getValue:&rect];
NSLog(@"value:%@",value); /*
从目录搜索扩展名为jpg的文件
*/ //NSFileManager fileManager = [NSFileManager defaultManager];
NSString home;
home = @"../Users/"; NSDirectoryEnumerator *direnum;
direnum = [fileManager enumeratorAtPath: home]; NSMutableArray *files = [[NSMutableArray alloc] init]; //枚举
NSString *filename;
while (filename = [direnum nextObject]) {
if([[filename pathExtension] hasSuffix:@"jpg"]){
[files addObject:filename];
}
} //快速枚举
//for(NSString *filename in direnum)
//{
// if([[filename pathExtension] isEqualToString:@"jpg"]){
// [files addObject:filename];
// }
//}
NSLog(@"files:%@",files); //枚举
NSEnumerator *filenum;
filenum = [files objectEnumerator];
while (filename = [filenum nextObject]) {
NSLog(@"filename:%@",filename);
} //快速枚举
//for(id object in files)
//{
// NSLog(@"object:%@",object);
//}
上一篇:再谈spring的循环依赖是怎么造成的?


下一篇:IOS数组按中文关键字以字母序排序