NSRange : 表示范围作用的结构体,3种方式创建
// 方式一
NSRange range;
location是一个以0开始的指数(index) ,,length(长度),他们都是NSUInteger类型
range.location = 17;
range.length = 4;
// 方式二
NSRange range = {17, 4};
// 方式三
// 推荐
NSRange range = NSRangeMake(17, 4);
使用例子:
下面这个例子,将输出lonely
NSString*homebrew = @"the road is lonely its crowd for it is not loved";
// Starting at position 12, get 6 characters
NSRange range=NSMakeRange (12, 6);
// This would also work:
// NSRange range = {12, 6};
NSLog (@"Beer shortname: %@", [homebrew substringWithRange:range]);
//反向搜索
NSRange range = [homebrew rangeOfString:@"ia" options:NSBackwardsSearch];
搜索字符串:
NSString*homebrew = @"the road is lonely its crowd for it is not loved";
NSRange range = [homebrew rangeOfString:@"lonely"];
// Did we find the string "lonely" ? 是否有lonely
if (range.length > 0)
NSLog(@"Range is: %@", NSStringFromRange(range));
例如获取一个数组的一个子集:
NSRange range =NSMakeRange(0,5);
NSArray*subArray = [self.states subarrayWithRange:range];
这样就获得了这个数组中0开始的5个元素的子集。
NSNumber:专门用来装基础类型的对象,把整型、单精度、双精度、字符型等基础类型存储为对象
//封装基本数据类型
int intValue =100;
float floatValue =3.14;
BOOL boolValue =YES;
char charValue='1'
NSNumber *intNumber = [[NSNumberalloc]initWithInt:intValue];
NSLog(@"intNumber is %@", intNumber);
NSNumber *floatNumber = [NSNumbernumberWithFloat:floatValue];
NSLog(@"floatNumber is %@", floatNumber);
NSNumber *boolNumber = [NSNumbernumberWithBool:boolValue];
NSLog(@"boolNumber is %@", boolNumber);
NSNumber *charNumber = [NSNumbernumberWithBool:charValue];
NSLog(@"charNumber is %@", charNumber);
//包装之后就可以放到容器中
NSArray*arr = @[intNumber, floatNumber,boolNumber,charNumber];
NSLog(@"arr is %@", arr);
//还原成基本数据类型
floatvalue = [floatNumber floatValue];
intvalue2= [intNumber intValue];
NSLog(@"value is %.2f",value);
NSLog(@"value2 is %d",value2);
//快速创建的方法
NSNumber *intNum =@80;//----> NSNumber *intNumber = [[NSNumber alloc] initWithInt:80];
NSNumber *floatNum =@3.14;// ---->[NSNumber numberWithFloat:3.14];
NSNumber *boolNum =@YES;// ---> [NSNumber numberWithBool:YES];
NSNumber *charNum = @'a';// ---> [NSNumber numberWithChar:'a'];
//运算
NSNumber*number = @(1+2);
//直接在数组中写
NSArray*arr1= @[@"string",@12, intNum, floatNum, boolNum, charNum,number];
NSLog(@"arr1 is %@", arr1);
//判断两个NSNumber是否相等
//这种比较也是可以跨不同对象的,比如:比较intNumber和floatNumber
BOOL ret = [intNumber isEqualToNumber:intNumber2];
//比较两个整型的NSNumber的大小
if ([intNumber compare:intNumber] == NSOrderedAscending) {
NSLog(@"<");
}else if([intNumber compare:intNumber2] == NSOrderedSame){
NSLog(@"=");
}else if([intNumber compare:intNumber2] == NSOrderedDescending){
NSLog(@">");
}
字典NSDictionary类、NSMutableDictionary类:关键字和其定义的集合,也被成为散列表或关联数组,使用的是键查询的优化存储方式
//初始化一组数组,存入字典中作为关键字 NSDictionary
NSNumber *num = [NSNumber numberWithInt:100];
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:num forKey:@"key1"];
//优化语法
//1.---------------------字典的创建
NSArray*array1= [NSArrayarrayWithObjects:@"zhangsan",@"zhangfei",nilnil];
NSArray*array2= [NSArrayarrayWithObjects:@"lisi",@"liping",nilnil];
//第一个元素:key:@"zhang" value:array1
//第二个元素:key:@"li" value:array2
NSDictionary*dict = [[NSDictionaryalloc]initWithObjectsAndKeys:array1,@"zhang",array2,@"li",nilnil];
NSLog(@"%@",dict);
//存放一个元素
NSDictionary*dict2= [NSDictionarydictionaryWithObject:array1forKey:@"zhang"];
//2.---------------------获取所有的key
NSArray*allKeys = [dictallKeys];
//3.---------------------获取所有的value
//可能为二维数组
NSArray*allValues = [dictallValues];
//4.---------------------通过key获取value
NSArray*values = [dictobjectForKey:@"zhang"];
//5.---------------------优化的语法
NSDictionary*dict3= @{@"zhangsan":array1,@"lisi":array2};
NSLog(@"%@",dict3);
NSArray*array4= dict3[@"zhang"];
//初始化多组数据
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"hello",@"key2",@"world",@"key3",@"csdn",@"key4", nil nil];
注意结尾是nil nil
//用一个字典初始化另外一个字典
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic2];
//打印输出
NSLog(@"dic1 : %@,dic2 : %@, dic3 : %@",dic1,dic2,dic3);
输出:
dic1 :{ key1 = 100;}
dic2 : { key2 = hello; key3 = world; key4 = csdn;}
dic3 : { key2 = hello; key3 = world; key4 = csdn;}
获取字典的值
//获取长度
int length = [dic2 count];
NSLog(@"dic2 length = %d",length);
//根据key获取key所对应的value
NSLog(@"key3 value = %@",[dic2 objectForKey:@"key3"]);
//可以获取所有的keys
NSArray *allkeys = [dic3 allKeys];
NSLog(@"NSarray allkey = %@",allkeys);
//可以获取所有的values
NSArray *allvalues = [dic3 allValues];
NSLog(@"NSarray allvalues = %@",allvalues);
输出:dic2 length = 3
key3 value = world
NSarray allkey = ( key4, key3, key2 )
NSarray allvalues = ( csdn, world, hello )
可变字典 NSMutableDictionary
NSMutableDictionary *dic4 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"one",@"key4",@"two",@"key5", nil nil]; //定义成空字典
NSMutableDictionary *dic5 = [NSMutableDictionary dictionary];
//将字典dic2整体添加到dic4钟
[dic4 addEntriesFromDictionary:dic2];
//添加一个元素 存在即替换内容
NSDictionary*dict2= [NSDictionarydictionaryWithObject:array1 forKey:@"zhang"];
[dic4 setValue:@"three" forKey:@"key6"];
//3.-------------删除元素
[md1removeObjectForKey:@"zhang"];//以key删除
[md1removeAllObjects];//删除所有元素
[md1removeObjectsForKeys:array1];//以value删除
//根据key获取value
NSLog(@"key6 = %@",[dic4 objectForKey:@"key6"]);
//删除指定key值的字典元素
[dic4 removeObjectForKey:@"key6"];
//将一个字典加到可变字典里面
dic4=[[NSMutableDictionary alloc]initWithCapacity:10];
[dic4 addObjectsFromArray:_arr];
字典的遍历
1)一般遍历
NSArray *keys4 = [dic4 allKeys]; //获取所有的key allValue 获取所有的value
for(int i=0;i<[dic4 count];i++) {
NSLog(@"dic4 key = %@,value=%@",[keys4 objectAtIndex:i],[dic4 objectForKey:[keys4 objectAtIndex:i]]);
}
输出:dic4 key = key3,value=world
dic4 key = key6,value=three
dic4 key = key4,value=csdn
dic4 key = key2,value=hello
dic4 key = key5,value=two
2)高效的for遍历
for (NSString *key in dic4) {
NSLog(@"dic4 key = %@ ,value = %@",key,[dic4 objectForKey:key]);
}
输出:dic4 key = key3,value=world
dic4 key = key6,value=three
dic4 key = key4,value=csdn
dic4 key = key2,value=hello
dic4 key = key5,value=two
3)枚举遍历
NSEnumerator *enum1 = [dic4 keyEnumerator];
//获取key,如果不为空,则进行偏移
id key = [enum1 nextObject]; while (key) {
NSLog(@"key = %@ ,value = %@ ",key,[dic4 objectForKey:key]);
key = [enum1 nextObject]; }
输出:dic4 key = key3,value=world
dic4 key = key6,value=three
dic4 key = key4,value=csdn
dic4 key = key5,value=two
扩展 单例的使用
.h
#import@interface ShowStart : NSObject
+(ShowStart *)showStart;
@property(strong,nonatomic) NSMutableDictionary *dic;
@end
.m
#import "ShowStart.h"
@implementation ShowStart
static ShowStart *usertelphonenum=nil;
+(ShowStart *)showStart{
if (usertelphonenum==nil) {
usertelphonenum=[[ShowStart alloc]init];
//一定要有大小
usertelphonenum.dic=[[NSMutableDictionary alloc]initWithCapacity:10];
}return usertelphonenum;}
数组 可变数组 NSArray NSMutableArray
//1.---------------------数组的创建
NSString*s1=@"zhangsan";
NSString*s2=@"lisi";
NSString*s3=@"wangwu";
//最后的nil相当于结束的标记
NSArray*array1= [[NSArrayalloc]initWithObjects:s1,s2,s3,nilnil];
//打印的时候会调用description方法
//相当于:array1.description
NSLog(@"%@",array1);
//使用类方法创建
array1= [NSArrayarrayWithObjects:s1,s2,s3,nilnil];
//创建一个数组,将源数组中的数据拿出来放进去
NSArray*array2= [NSArrayarrayWithArray:array1];
//2.----------------------objectAtIndex
//访问数组中的数据,数组中存放的是对象的指针
NSString*str1= [array1objectAtIndex:0];
//3.----------------------count
//获取数组元素中的个数
NSUInteger count = [array1count];//返回的是一个无符号数值
//4.----------------------containsObject
//判断数组中是否包含某一个对象,判断的是指针对象值,不是对象中的值
BOOLisContains = [array1containsObject:@"zhangsan"];
//5.----------------------indexOfObject
//返回一个对象在数组中的下标值
NSUInteger index = [array1indexOfObject:@"zhangsan"];
if(index == NSNotFound){
//没有找到
}else{
//找到了
}
//6.----------------------componentsJoinedByString
//数组中存放的如果是字符串的话,可以使用连接符将其所有的元素进行连接
//注意数组中的元素必须都是字符串
NSString*content = [array1componentsJoinedByString:@","];
//7.----------------------lastObject
//访问数组最后一个元素
NSString*lastObj = [array1 lastObject];
//8.----------------------arrayByAddingObject
//在原来的数组后面追加元素,返回一个新的数组对象,因为他是不可变的
NSArray*array3= [array1arrayByAddingObject:@"zhaoliu"];
//数组的遍历
for(inti=0;i
NSString*str = [array1objectAtIndex:i];
NSLog(@"%@",str);
}
//快速遍历
for(NSString*s in array1){
NSLog(@"%@",s);
}
//xcode4.4以后,编译器对数组的创建和访问语法做了优化
NSArray*array7= @[s1,s2,s3];
NSString*s = array7[0];
NSMutableArray
//1.---------------------创建可变数组
NSString*str1=@"zhangsan";
NSString*str2=@"lisi";
NSString*str3=@"wangwu";
NSMutableArray*mArray1= [[NSMutableArrayalloc]initWithObjects:str1,str2,str3,nilnil];
//下面的这种方式创建的数组是错误的
//下面的这种方式是创建不可变数组的方式,不能哟关于可变数组的创建
//NSMutableArray *array1 = @[str1,str2,str3];
//先开辟5个空间,用于存储元素,当存储的元素超过了5个,数组会自动增大空间
NSMutableArray*mArray2= [[NSMutableArrayalloc]initWithCapacity:5];
//使用类方法创建
NSMutableArray*mArray3= [NSMutableArrayarrayWithCapacity:5];
//2.---------------------addObject
//添加元素的方法
[mArray1addObject:str1];
[mArray1addObject:str2];
//添加数组,把mArray1中的所有元素全部添加到mArray2中
[mArray2addObjectsFromArray:mArray1];
NSLog(@"mArray3 = %@",mArray2);
//二维数组
//这个是将mArray1添加到mArray2数组中,这样mArray2就变成了二维数组了
[mArray2addObject:mArray1];
//3.---------------------insertObject
//在指定的位置上插入特定元素
[mArray2insertObject:@"def"atIndex:0];
//4.---------------------replaceObjectAdIdex
//替换元素
[mArray2replaceObjectAtIndex:0withObject:@"aaa"];
//5.---------------------exchangeObjectAtIndex
//互换两个元素的位置
[mArray2exchangeObjectAtIndex:0withObjectAtIndex:3];
//6.---------------------removeObjectAdIndex
//删除指定位置的元素
[mArray2removeObjectAtIndex:0];
//删除最后一个元素
[mArray2removeLastObject];
//删除指定的对象
[mArray2removeObject:@"lisi"];
//删除所有的对象/清空列表
[mArray2removeAllObjects];
注:OC中没有泛型的概念,所以对于数组中存放了不同类型的值,在运行的时候会报错的,这个和Java相比,操作集合类的时候安全性就差了点。所以我们在操作集合类的时候需要注意的地方。
NSString类
一、NSString的初始化方法:
+(NSString*)stringWithString:
NSString *str=@"hello";
NSString *str1=[NSString stringWithString:str];
+(NSString*)stringWithFormat:
NSString
*str2=[NSStringstringWithFormat:@"hello%d",10];
-(NSString*)initWithString:
NSString *str3=[[NSString alloc]initWithString:@"hello"];
-(NSString*)initWithFormat:
NSString *str4=[[NSString
alloc]initWithFormat:@"hello"];
二、从文件中读取字符串:
+(NSString*)stringWithContentsOfFile:encoding: error:
NSString
*str5=[NSStringstringWithContentsOfFile:@"/Users/stjy/Desktop/zh/oc_class8
NSString等/oc_class8
NSString等/File1"encoding:NSUTF8StringEncodingerror:nil];
三、从网络中获取字符串:
+(NSString*)stringWithContentsOfURL: encoding:
error:
NSURL *url=[NSURL
alloc]initWithString:@"http://www.bluejob.cn/career/lists/1/"];//创建URL对象
NSError *error=nil;
NSString *str6=[NSString stringWithContentsOfURL:urlencoding:NSUTF8StringEncodingerror:&error];
四、获取指定范围字符串并进行一系列操作
1、获取指定范围的子字符串,NSRange是一个结构体类型,包含起始位置和长度两个int型变量
-(NSString *)substringWithRange:
NSString *str7=@"helloworld";
NSRange range=NSMakeRange(3,3);//创建范围结构体
NSString *subStr7=[str7
substringWithRange:range];//获取指定范围的子字符串
2.字符串替换,指定范围
-(NSString*)stringByReplacingCharactersInRange: withString:
NSString *str8=[str7 stringByReplacingCharactersInRange:rangewithString:@"*"];//替换字符范围为(3,3)的值为*
3、求子字符串在母串中的范围,返回NSRange类型
-(NSRange)rangeOfString:
4.求指定范围的子字符串,C函数
NSRange ra=[str7 rangeOfString:subStr7];
NSLog(@"%@",NSStringFromRange(ra));
5.比较两个字符串内容是否相同
- (BOOL)isEqualToString:(NSString *)aString
6.比较两个字符串的大小
- (NSComparisonResult)compare:(NSString
*)aString
enum {NSOrderedAscending= -1,NSOrderedSame,NSOrderedDescending};typedef NSInteger NSComparisonResult; //枚举类型
7.分割字符串
- (NSArray*)componentsSeparatedByString:(NSString *)separator
1.截取字符串
NSString*string =@"sdfsfsfsAdfsdf";
string = [string substringToIndex:7];//截取下标7之前的字符串
NSLog(@"截取的值为:%@",string);
[string substringFromIndex:2];//截取下标2之后的字符串
NSLog(@"截取的值为:%@",string);
2.匹配字符串
NSString*string =@"sdfsfsfsAdfsdf";
NSRangerange = [stringrangeOfString:@"f"];//匹配得到的下标
NSLog(@"rang:%@",NSStringFromRange(range));
string = [string substringWithRange:range];//截取范围类的字符串
NSLog(@"截取的值为:%@",string);
3.分隔字符串
NSString*string =@"sdfsfsfsAdfsdf";
NSArray *array = [string componentsSeparatedByString:@"A"]; //从字符A中分隔成2个元素的数组
NSLog(@"array:%@",array); //结果是adfsfsfs和dfsdf
日期
NSDate *date1=[NSDate date];//获得当前日期NSLog(@"%@",date1);
//结果:2014-07-16 07:25:28 +0000
NSDate *date2=[NSDate dateWithTimeIntervalSinceNow:100];//在当前日期的基础上加上100秒,注意在ObjC中多数时间单位都是秒NSLog(@"%@",date2);
//结果:2014-07-16 07:27:08 +0000
NSDate *date3=[NSDate distantFuture];//随机获取一个将来的日期
NSLog(@"%@",date3);
//结果:4001-01-01 00:00:00 +0000
NSTimeInterval time=[date2 timeIntervalSinceDate:date1];//日期之差,返回单位为秒
NSLog(@"%f",time);
//结果:100.008833
NSDate *date5=[date1 earlierDate:date3];//返回比较早的日期
NSLog(@"%@",date5);
//结果:2014-07-16 07:25:28 +0000
//日期格式化
NSDateFormatter *formater1=[[NSDateFormatter alloc]init];
formater1.dateFormat=@"yy-MM-dd HH:mm:ss";
NSString *datestr1=[formater1 stringFromDate:date1];
NSLog(@"%@",datestr1);
//结果:14-07-16 15:25:28
//字符串转化为日期
NSDate *date6=[formater1 dateFromString:@"14-02-14 11:07:16"];
NSLog(@"%@",date6);
//结果:2014-02-14 03:07:16 +0000
不可变字符串
/**字符串操作*/
voidtest1(){char*str1="C string";//这是C语言创建的字符串
NSString *str2=@"OC string";
//ObjC字符串需要加@,并且这种方式创建的对象不需要自己释放内存
//下面的创建方法都应该释放内存arc不需要
NSString *str3=[[NSString alloc] init];
str3=@"OC string";
NSString *str4=[[NSString alloc] initWithString:@"Objective-C string"];
NSString *str5=[[NSString alloc] initWithFormat:@"age is %i,name is %.2f",19,1.72f];
NSString *str6=[[NSString alloc] initWithUTF8String:"C string"];//C语言的字符串转换为ObjC字符串
//以上方法都有对应静态方法(一般以string开头),不需要管理内存(系统静态方法一般都是自动释放)
NSString *str7=[NSString stringWithString:@"Objective-C string"];
NSLog(@"\"Hello world!\" to upper is %@",[@"Hello world!"uppercaseString]);
//结果:"Hello world!" to upper is HELLO WORLD!
NSLog(@"\"Hello world!\" to lowwer is %@",[@"Hello world!"lowercaseString]);
//结果:"Hello world!" to lowwer is hello world!
//首字母大写,其他字母小写
NSLog(@"\"Hello world!\" to capitalize is %@",[@"Hello world!"capitalizedString]);
//结果:"Hello world!" to capitalize is Hello World!
BOOL result= [@"abc"isEqualToString:@"aBc"];
NSLog(@"%i",result);
//结果:0NSComparisonResult result2= [@"abc"compare:@"aBc"];
//如果是[@"abc" caseInsensitiveCompare:@"aBc"]则忽略大小写比较if(result2==NSOrderedAscending){
NSLog(@"left
}else if(result2==NSOrderedDescending){
NSLog(@"left>right.");
}else if(result2==NSOrderedSame){
NSLog(@"left=right.");
}
//结果:left>right.}voidtest3(){
NSLog(@"has prefix ab? %i",[@"abcdef"hasPrefix:@"ab"]);
//结果:has prefix ab? 1
NSLog(@"has suffix ab? %i",[@"abcdef"hasSuffix:@"ef"]);
//结果:has suffix ab? 1
NSRange range=[@"abcdefabcdef"rangeOfString:@"cde"];
//注意如果遇到cde则不再往后面搜索,如果从后面搜索或其他搜索方式可以设置第二个options参数
if(range.location==NSNotFound){
NSLog(@"not found.");
}else{
NSLog(@"range is %@",NSStringFromRange(range));
}
//结果:range is {2, 3}}//字符串分割voidtest4(){
NSLog(@"%@",[@"abcdef"substringFromIndex:3]);
//从第三个索引开始(包括第三个索引对应的字符)截取到最后一位
//结果:def
NSLog(@"%@",[@"abcdef"substringToIndex:3]);
////从0开始截取到第三个索引(不包括第三个索引对应的字符)
//结果:abc
NSLog(@"%@",[@"abcdef"substringWithRange:NSMakeRange(2, 3)]);
//结果:cdeNSString *str1=@"12.abcd.3a";
NSArray *array1=[str1 componentsSeparatedByString:@"."];
//字符串分割NSLog(@"%@",array1);
/*结果:
(
12,
abcd,
3a
)
*/}
//其他操作voidtest5(){
NSLog(@"%i",[@"12"intValue]);//类型转换
//结果:12
NSLog(@"%zi",[@"hello world,世界你好!"length]);
//字符串长度注意不是字节数
//结果:17
NSLog(@"%c",[@"abc"characterAtIndex:0]);
//取出制定位置的字符
//结果:aconst char*s=[@"abc"UTF8String];
//转换为C语言字符串
NSLog(@"%s",s);
//结果:abc}
可变字符串
/*可变字符串,注意NSMutableString是NSString子类*/
//注意虽然initWithCapacity分配字符串大小,但是不是绝对的不可以超过此范围,声明此变量对性能有好处
NSMutableString *str1= [[NSMutableString alloc] initWithCapacity:10];
[str1 setString:@"hello"];//设置字符串NSLog(@"%@",str1);
/结果:hello[str1 appendString:@",world!"];
//追加字符串
NSLog(@"%@",str1);
//结果:hello,world![str1 appendFormat:@"我的年龄是%i。dear,I love you.",18];
NSLog(@"%@",str1);
//结果:hello,world!我的年龄是18。dear,I love you.
//替换字符串
NSRange range=[str1 rangeOfString:@"dear"];
[str1 replaceCharactersInRange:range withString:@"Honey"];
NSLog(@"%@",str1);
//结果:hello,world!我的年龄是18。Honey,I love you.
//插入字符串
[str1 insertString:@"My name is Kenshin."atIndex:12];
NSLog(@"%@",str1);
//结果:hello,world!My name is Kenshin.我的年龄是18。Honey,I love you.
//删除指定字符串[str1 deleteCharactersInRange:[str1 rangeOfString:@"My name is Kenshin."]];
//删除指定范围的字符串NSLog(@"%@",str1);//结果:hello,world!我的年龄是18。Honey,I love you.
参考:iOS开发系列—Objective-C之Foundation框架 来自崔江涛(KenshinCui),
有一些找不到出处,都是百度找到的,如果需要请自行百度 这么长肯定没人看。。。