最近自己在和朋友做一项目,碰到字符串的截取和分割,总结了一部分代码,防止自己下次忘掉。
//下面代码用冒号和空格对字符串进行分割,并加入字典当中,用于通知中的字典
NSArray *array = [soapResults componentsSeparatedByString:@":"];
NSString *address=[array objectAtIndex:1];
NSArray *addre=[address componentsSeparatedByString:@" "];
NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",[addre objectAtIndex:0]] forKey:@"sheng"];
[dic setObject:[NSString stringWithFormat:@"%@",[addre objectAtIndex:1]] forKey:@"shi"];
[dic setObject:[NSString stringWithFormat:@"%@",[addre objectAtIndex:2]] forKey:@"yunyingshang"];
关于字符串的截取,代码如下:
int b= [[a substringWithRange:NSMakeRange(4,2)] intValue];
该句代码意思是从第4个字符开始截取,长度为2个字符,并将a转换成整数型
NSString *b = [a substringToIndex:4];
该句代码意思是字符串截取到第4位,(且第4位不算在内)
NSString *b = [a substringFromIndex:4];
该句代码的意思是字符串从第4位开始截取,直到最后(包括第4位)
接下来说说遇到的通知问题:由于在一个类中做了数据的操作,导致数据无法传到另外的viewController,所以使用了通知,用来告知数据的操作并传递操作后的数据。
首先在类里面数据操作前注册通知。
//注册通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(callBack:) name:@"back" object:nil];
然后在,数据操作后,发送通知:
//发送通知
[[NSNotificationCenter defaultCenter]postNotificationName:@"back" object:self userInfo:dic];
最后在这个类里面写出相应的方法:
//回调方法,必须写
-(void)callBack:(NSNotification *)notificition{
NSLog(@"发送通知");
}
接下来在你需要接收通知的viewController里面创建监听者:
//监听通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callBack:) name:@"back" object:nil];
并执行回调的方法:
//回调方法
-(void)callBack:(NSNotification *)notificition{
//监听接收通知
NSDictionary *dic=[notificition userInfo];
NSString *centerx=[dic objectForKey:@"sheng"];
NSString *centery=[dic objectForKey:@"shi"];
NSString *centertag=[dic objectForKey:@"yunyingshang"];
NSLog(@"sheng=%@,shi=%@,yunyingshang=%@",centerx,centery,centertag);
NSString *address=[NSString stringWithFormat:@"%@ %@",centerx,centery];
contactsLab.text=textFieldYourPhoneNumber.text;
locationLab.text=address;
mobileLab.text=centertag;
}
这样可以达到了我所要的效果。