NSdata 与 NSString,Byte数组,UIImage 的相互转换
1. NSData 与 NSString
NSData-> NSString
NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
NSString->NSData
NSString *aString = @"1234abcd";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];
2.NSData 与 Byte
NSData-> Byte数组
NSString *testString = @"1234567890";
NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];
for(int i=0;i<[testData length];i++)
printf("testByte = %d\n",testByte[i]);
Byte数组-> NSData
Byte byte[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
NSData *adata = [[NSData alloc] initWithBytes:byte length:24];
Byte数组->16进制数
Byte *bytes = (Byte *)[aData bytes];
NSString *hexStr=@"";
for(int i=0;i<[encryData length];i++)
{
NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff]; ///16进制数
if([newHexStr length]==1)
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
else
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
NSLog(@"bytes 的16进制数为:%@",hexStr);
16进制数->Byte数组
///// 将16进制数据转化成Byte 数组
NSString *hexString = @"3e435fab9c34891f"; //16进制字符串
int j=0;
Byte bytes[128];
///3ds key的Byte 数组, 128位
for(int i=0;i<[hexString length];i++)
{
int int_ch; /// 两位16进制数转化后的10进制数
unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
int int_ch1;
if(hex_char1 >= '0' && hex_char1 <='9')
int_ch1 = (hex_char1-48)*16; //// 0 的Ascll - 48
else if(hex_char1 >= 'A' && hex_char1 <='F')
int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
else
int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
i++;
unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
int int_ch2;
if(hex_char2 >= '0' && hex_char2 <='9')
int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
else if(hex_char1 >= 'A' && hex_char1 <='F')
int_ch2 = hex_char2-55; //// A 的Ascll - 65
else
int_ch2 = hex_char2-87; //// a 的Ascll - 97
int_ch = int_ch1+int_ch2;
NSLog(@"int_ch=%d",int_ch);
bytes[j] = int_ch; ///将转化后的数放入Byte数组里
j++;
}
NSData *newData = [[NSData alloc] initWithBytes:bytes length:128];
NSLog(@"newData=%@",newData);
3. NSData 与 UIImage
NSData->UIImage
UIImage *aimage = [UIImage imageWithData: imageData];
//例:从本地文件沙盒中取图片并转换为NSData
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *name = [NSString stringWithFormat:@"ceshi.png"];
NSString *finalPath = [path stringByAppendingPathComponent:name];
NSData *imageData = [NSData dataWithContentsOfFile: finalPath];
UIImage *aimage = [UIImage imageWithData: imageData];
UIImage-> NSData
NSData *imageData = UIImagePNGRepresentation(aimae);
原文网址:http://blog.sina.com.cn/s/blog_6268f10201015ak8.html
以binary来收藏容纳文件
NSData生成:
NSDictionary *dic =[NSDictionary dictionaryWithObject:@"hello" forKey:@"KEY"];
NSData *d = [NSKeyedArchiver archivedDataWithRootObject:dic];
从文件生成NSData:
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"hello" ofType:@"png"];
NSData *d = [[NSData alloc] initWithContentsOfFile: path];
取得元素长度:
int i = [d length];
NSData型转成NSDictionary型:
NSDictionary *reverse = [NSKeyedUnarchiver unarchiveObjectWithData: d];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSString *strPath = @"/Users/user/Desktop/jkk.txt";
NSLog(@"string = %@",[[NSString alloc]initWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:Nil]);
NSData *strData = [[NSData alloc]initWithContentsOfFile:strPath];
NSLog(@"size = %d字节; strData = %@",strData.length,strData.description);
NSUInteger len = [strData length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [strData bytes], len);
for (int i = 0; i < len; i++) {
printf("%c",byteData[i]);
}
NSData *Data222 = [[NSData alloc]initWithBytes:byteData length:len];
NSLog(@"Data222 : %@",Data222);
NSRange rangeData = {0,3};
NSData *subData = [strData subdataWithRange:rangeData];
NSLog(@"subData : %@",subData);
NSData *Data333 = [[NSData alloc]initWithData:subData];
NSLog(@"Data333: %@",[[NSString alloc]initWithData:Data333 encoding:NSUTF8StringEncoding]);
How to turn 4 bytes into a float in objective-c from NSData
原文网址:http://stackoverflow.com/questions/30608669/how-to-turn-4-bytes-into-a-float-in-objective-c-from-nsdata
NSData* data = [NSData dataWithContentsOfFile:@"/tmp/java/test.dat"];
int32_t bytes;
[data getBytes:&bytes length:sizeof(bytes)];
bytes = OSSwapBigToHostInt32(bytes);
float number;
memcpy(&number, &bytes, sizeof(bytes));
NSLog(@"Float %f", number);
NSString与int和float的相互转换
NSString *tempA = @"123";
NSString *tempB = @"456";
1,字符串拼接
NSString *newString = [NSString stringWithFormat:@"%@%@",tempA,tempB];
2,字符转int
int intString = [newString intValue];
3,int转字符
NSString *stringInt = [NSString stringWithFormat:@"%d",intString];
4,字符转float
float floatString = [newString floatValue]
5,float转字符
NSString *stringFloat = [NSString stringWithFormat:@"%f",intString];
iPhone: @selector 里面的方法名加参数 NSTimer and that thing called userInfo
NSTimer携带传递值
NSTimer有个属性 叫userInfo,下面的方法的第四个参数userInfo
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
userinfo用NSTimer的实例可以获得,返回类型是 id
[timer userInfo];
[NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(handleTimer:) userInfo:@"参数" repeats:YES];
用的时候只要在下面函数里调用强制转换的userinfo就行,
-(void)handleTimer:(NSTimer*)timer
{
//这里使用(NSString *)[timer userInfo]
}
-(void)handleTimer:(NSTimer*)timer
这里最好用id做参数
-(void)handleTimer:(id)timer
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
if(oldView != nil){
[dict setObject:oldView forKey:@"oldView"];
}
if(newView != nil){
[dict setObject:newView forKey:@"newView"];
}
[NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(onTimer:) userInfo:dict repeats:NO];
[dict release];
- (void)onTimer:(NSTimer *)timer {
UIView *oldView = [[timer userInfo] objectForKey:@"oldView"];
UIView *newView = [[timer userInfo] objectForKey:@"newView"];
[UIView animateWithDuration:2.0 delay:0
options:UIViewAnimationOptionAllowUserInteraction
animations:^{
oldView.alpha = 0.0;
newView.alpha = 1.0;
}
4.
在学习OC代码的时候,编译oc .m文件有如下两种方式(1) clang -fobjc-arc -framework Foundation Hello.m -o hello.out
./hello.out
(2) 用xcode编译.m后生成的可执行文件hello和源码hello.m不在同一个目录
通过右击 hello, show in finder可以找到hello可执行文件
或者通过下面的代码查看
To get the path to your file use
NSString * myFile = [[NSBundle mainBundle]pathForResource:@"Alert" ofType:@"txt"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath: myFile ]){
NSLog(@"good");
}
这个问题是在学习NSFileManger的时候,使用NSFileManger创建的文件,在源码的文件夹中找不到,
上面的方式可以查看到实际的路径:
/Users/yqf/Library/Developer/Xcode/DerivedData/NSFileManagerTest2-eaeuwbogilljalgvxymvlvdqwjwb/Build/Products/Debug/NSFile
5. Xcode workSpace与Project配置
原文网址:http://blog.sina.com.cn/s/blog_13edf9b370102w8r4.html
方式一 右键add
WorkSpace中添加已有的工程-方式1.png
- 注意点1 选择工程时,选后缀名为
.xcodeproj
的工程配置文件,而不是选择整个工程的父文件夹。
方式二 直接拖
- 注意点1 拖到面板的时候,鼠标要放在最上方,不然会导致工程
WorkSpace中添加已有的工程-方式二-1.png - 注意点2 只能托后缀名为
.xcodeproj
的工程配置文件
WorkSpace中添加已有的工程-方式二-2.png
方式三
- 直接选择菜单栏中的new->project
但是必须选择ADD TO WorkSpace
WorkSpace中添加已有的工程-方式三.png
6. 用NSScanner判断String内容是否为整型或者浮点型数据
原文网址:http://cocoa-chen.github.io/blog/2014/10/27/yong-nsscannerpan-duan-stringnei-rong-shi-fou-wei-zheng-xing-huo-zhe-fu-dian-xing-shu-ju/
在开发的过程中会遇到各种各样的需求,比如需要判断一个NSString的变量内容是否为Int数据或者Float数据,这时候可以用NSScanner来简单的判断下
1.判断NSString是否为int内容
1 | - (BOOL)isPureInt:(NSString *)string{ |
调用测试如下:
1 | NSString *pureIntString = @"123"; |
2.判断NSString是否为float内容
1 | - (BOOL)isPureFloat:(NSString *)string{ |
调用测试如下:
1 | NSString *pureFloatString = @"1.23"; |
NSScanner还提供其他的API来检测对应的数据类型,遇到对应的需求大家可以尝试使用一下!
7. Objective-C 拆分字符串成数组(类似java 的 split)
在很多语言如 java , ruby , python中都有将字符串切分成数组或者将数组元素以某个间隔字符串间隔形成新的数组。 其实NSArray也提供了这样的功能。
使用-componentsSeparatedByString:来切分NSArray。 如:
引用
NSString *string = @”one:two:three”;
NSArray *aArray = [string componentsSeparatedByString:@":"];
用-componentsJoinedByString:来合并NSArray中的各个元素并创建一个新的字符串,如:
string = [aArray componentsJoinedByString:@","];
这样,上面的数组就中的各个元素就以”,”分割形成一个字符串。
8. ios 开发 NSArray 排序 (根据NSString的值排序)
- NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"1",@"3",@"5",@"40" nil];</span></p>NSArray *sorteArray = [array sortedArrayUsingComparator:^(id obj1, id obj2){
- if ([obj1 integerValue] > [obj2 integerValue]) {
- return (NSComparisonResult)NSOrderedDescending;
- }
- if ([obj1 integerValue] < [obj2 integerValue]) {
- return (NSComparisonResult)NSOrderedAscending;
- }
- return (NSComparisonResult)NSOrderedSame;
- }];
- NSLog(@"%@",sorteArray); //从小到大
- NSArray *array2 = [array sortedArrayUsingComparator:^(id obj1, id obj2){
- if ([obj1 integerValue] > [obj2 integerValue]) {
- return (NSComparisonResult)NSOrderedAscending;
- }
- if ([obj1 integerValue] < [obj2 integerValue]) {
- return (NSComparisonResult)NSOrderedDescending;
- }
- return (NSComparisonResult)NSOrderedSame;
- }];
- NSLog(@"%@",array2);
以上包含了有从小到大的排序,也包含有大到小的排序
如果是针对字符串的排序,有更好的方法,
[cpp] view plain copy
- NSArray *ary = @[@"a3",@"a1",@"a2",@"a10",@"a24"];
- NSLog(@"%@",ary);
- NSArray *myary = [ary sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
- return (NSComparisonResult)[obj1 compare:obj2 options:NSNumericSearch];
- }];
- NSLog(@"%@",myary);
- 结果
- ( a3,a1, a2, a10, a24 )
- ( a1, a2,a3, a10, a24 )
[cpp] view plain copy
- NSArray *ary = @[@"a3",@"a1",@"a2",@"a24",@"a14"];
- NSLog(@"%@",ary);
- NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列,no,降序排列
- NSArray *myary = [ary sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];//注意这里的ary进行排序后会生产一个新的数组指针,myary,不能在用ary,ary还是保持不变的。
- NSLog(@"%@",myary);
- // (a3, a1, a2,a24,a14)
- // (a3, a24, a2, a14, a1)
[cpp] view plain copy
- [ary sortedArrayUsingSelector:@selector(compare:)];//这个是一直默认升序
8. 判断NSString是否包含某个字符串
在iOS8以后,还可以用下面的方法来判断是否包含某字符串:
//在iOS8中你可以这样判断
NSString *str = @"hello world";
if ([str containsString:@"world"]) {
NSLog(@"str 包含 world");
} else {
NSLog(@"str 不存在 world");
}
29. objective-c 下面int 和 NSData数据 互相转换的方法
int i = 1;
NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];
int i;
[data getBytes: &i length: sizeof(i)];