NSdata 与 NSString,Byte数组,UIImage 的相互转换

原文网址:http://www.cnblogs.com/jacktu/archive/2011/11/08/2241528.html

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
方式三
    1. 直接选择菜单栏中的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
2
3
4
5
6
7
8
- (BOOL)isPureInt:(NSString *)string{
if (!string) {
return NO;
}
NSScanner *_scanner = [NSScanner scannerWithString:string];
int val;
return [_scanner scanInt:&val] && [_scanner isAtEnd];
}
调用测试如下:
1
2
3
4
5
6
NSString *pureIntString = @"123";
NSString *noPureIntString = @"123ab";
BOOL isPure1 = [self isPureInt:pureIntString];
NSLog(@"'%@'字符串%@int内容的字符串",pureIntString,isPure1 ? @"是" : @"不是");
BOOL isPure2 = [self isPureInt:noPureIntString];
NSLog(@"'%@'字符串%@int内容的字符串",noPureIntString,isPure2 ? @"是" : @"不是");
2.判断NSString是否为float内容
1
2
3
4
5
6
7
8
- (BOOL)isPureFloat:(NSString *)string{
if (!string) {
return NO;
}
NSScanner* scan = [NSScanner scannerWithString:string];
float val;
return [scan scanFloat:&val] && [scan isAtEnd];
}
调用测试如下:
1
2
3
4
5
6
NSString *pureFloatString = @"1.23";
NSString *nopureFloatString = @"1.23a";
BOOL isPure1 = [self isPureFloat:pureFloatString];
NSLog(@"'%@'字符串%@float内容的字符串",pureFloatString,isPure1 ? @"是" : @"不是");
BOOL isPure2 = [self isPureFloat:nopureFloatString];
NSLog(@"'%@'字符串%@float内容的字符串",nopureFloatString,isPure2 ? @"是" : @"不是");
NSScanner还提供其他的API来检测对应的数据类型,遇到对应的需求大家可以尝试使用一下!

7.  Objective-C 拆分字符串成数组(类似java 的 split)

原文网址:http://blog.csdn.net/sirodeng/article/details/8306288

在很多语言如 java , ruby , python中都有将字符串切分成数组或者将数组元素以某个间隔字符串间隔形成新的数组。 其实NSArray也提供了这样的功能。

使用-componentsSeparatedByString:来切分NSArray。 如:

引用
NSString *string = @”one:two:three”; 
NSArray *aArray = [string componentsSeparatedByString:@":"];

用-componentsJoinedByString:来合并NSArray中的各个元素并创建一个新的字符串,如: 
string = [aArray componentsJoinedByString:@","];

这样,上面的数组就中的各个元素就以”,”分割形成一个字符串。

8. ios 开发 NSArray 排序 (根据NSString的值排序)

原文网址:http://blog.csdn.net/wenluma/article/details/8705272

  1. NSMutableArray *array =  [[NSMutableArray alloc] initWithObjects:@"1",@"3",@"5",@"40" nil];</span></p>NSArray *sorteArray = [array sortedArrayUsingComparator:^(id obj1, id obj2){
  2. if ([obj1 integerValue] > [obj2 integerValue]) {
  3. return (NSComparisonResult)NSOrderedDescending;
  4. }
  5. if ([obj1 integerValue] < [obj2 integerValue]) {
  6. return (NSComparisonResult)NSOrderedAscending;
  7. }
  8. return (NSComparisonResult)NSOrderedSame;
  9. }];
  10. NSLog(@"%@",sorteArray);            //从小到大
  11. NSArray *array2 = [array sortedArrayUsingComparator:^(id obj1, id obj2){
  12. if ([obj1 integerValue] > [obj2 integerValue]) {
  13. return (NSComparisonResult)NSOrderedAscending;
  14. }
  15. if ([obj1 integerValue] < [obj2 integerValue]) {
  16. return (NSComparisonResult)NSOrderedDescending;
  17. }
  18. return (NSComparisonResult)NSOrderedSame;
  19. }];
  20. NSLog(@"%@",array2);

以上包含了有从小到大的排序,也包含有大到小的排序

如果是针对字符串的排序,有更好的方法,

[cpp] view plain copy

  1. NSArray *ary = @[@"a3",@"a1",@"a2",@"a10",@"a24"];
  2. NSLog(@"%@",ary);
  3. NSArray *myary = [ary sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
  4. return (NSComparisonResult)[obj1 compare:obj2 options:NSNumericSearch];
  5. }];
  6. NSLog(@"%@",myary);
  7. 结果
  8. ( a3,a1, a2, a10, a24 )
  9. ( a1, a2,a3, a10, a24 )
  1. NSArray *ary = @[@"a3",@"a1",@"a2",@"a24",@"a14"];
  2. NSLog(@"%@",ary);
  3. NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列,no,降序排列
  4. NSArray *myary = [ary sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];//注意这里的ary进行排序后会生产一个新的数组指针,myary,不能在用ary,ary还是保持不变的。
  5. NSLog(@"%@",myary);
  6. //    (a3, a1, a2,a24,a14)
  7. //    (a3, a24, a2, a14, a1)
  1. [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数据 互相转换的方法

原文网址:http://blog.csdn.net/ixfly/article/details/7662096
int i = 1;
NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];
int i;
[data getBytes: &i length: sizeof(i)];

Objective-C 记录的更多相关文章

  1. Automake

    Automake是用来根据Makefile.am生成Makefile.in的工具 标准Makefile目标 'make all' Build programs, libraries, document ...

  2. 刨根问底Objective-C Runtime

    http://chun.tips/blog/2014/11/05/bao-gen-wen-di-objective%5Bnil%5Dc-runtime-(2)%5Bnil%5D-object-and- ...

  3. Sublime Text3 使用记录

    Sublime Text 3 使用记录 来看下本文的大纲吧 介绍下,我的环境      操作系统:win10 64bit      sublime Text  3 版本:3143 那么就开始啦. 一. ...

  4. 刨根问底Objective-C Runtime(4)- 成员变量与属性

    http://chun.tips/blog/2014/11/08/bao-gen-wen-di-objective[nil]c-runtime(4)[nil]-cheng-yuan-bian-lian ...

  5. 记一次debug记录:Uncaught SyntaxError: Unexpected token ILLEGAL

    在使用FIS3搭建项目的时候,遇到了一些问题,这里记录下. 这里是发布搭建代码: // 代码发布时 fis.media('qa') .match('*.{js,css,png}', { useHash ...

  6. nginx配置反向代理或跳转出现400问题处理记录

    午休完上班后,同事说测试站点访问接口出现400 Bad Request  Request Header Or Cookie Too Large提示,心想还好是测试服务器出现问题,影响不大,不过也赶紧上 ...

  7. Kali对wifi的破解记录

    好记性不如烂笔头,记录一下. 我是在淘宝买的拓实N87,Kali可以识别,还行. 操作系统:Kali 开始吧. 查看一下网卡的接口.命令如下 airmon-ng 可以看出接口名称是wlan0mon. ...

  8. 2015 西雅图微软总部MVP峰会记录

    2015 西雅图微软总部MVP峰会记录 今年决定参加微软MVP全球峰会,在出发之前本人就已经写这篇博客,希望将本次会议原汁原味奉献给大家 因为这次是本人第一次写会议记录,写得不好的地方希望各位园友见谅 ...

  9. 分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)

    分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间) 很多时候我们都需要计算数据库中各个表的数据量和每行记录所占用空间 这里共享一个脚本 CREATE TABLE #tab ...

  10. 我是如何在SQLServer中处理每天四亿三千万记录的

    首先声明,我只是个程序员,不是专业的DBA,以下这篇文章是从一个问题的解决过程去写的,而不是一开始就给大家一个正确的结果,如果文中有不对的地方,请各位数据库大牛给予指正,以便我能够更好的处理此次业务. ...

随机推荐

  1. JS 日期格式转换

    //Json 数据年月日 返回 直接传入参数 如/Date(1379433600000)/ function GetDate(date) { if (date == null) return null ...

  2. HTML5的简介

    前言:作为IOS开发工程师,终会接触到网页前端开发,甚至可能会有 用HTML5开发IOS的app客户端的需求.比如现在上架的app就有比如理财类型的app有的就用HTML开发的,从理财类型的app需求 ...

  3. LAMP虚拟主机配置以及控制目录访问

    3.基于域名的虚拟主机配置 NameVirtualHost192.168.3.32:80#apache2.2.xx版本需要开启此选项,而且要和下面的保持一致:2.4.x版本就不需要此项设置了 < ...

  4. (转载)使用ADOConnet.BeginTrans后,出现错误提示:无法在此会话中启动更多的事务?

    Q: 三层结构,在服务器端使用adoconnection连接到sqlserver2000,然后想在 datasetprovider的beforupdaterecord中使用语句: try adocon ...

  5. Nginx+Keepalived主备负载均衡

    实验环境及软件版本: CentOS版本:    6.6(2.6.32.-504.el6.x86_64) nginx版本:     nginx-1.6.2 keepalived版本:keepalived ...

  6. Mysql zip压缩包安装

    解压mysql.zip 配置环境变量(略) 配置my-default.ini 配置文件 安装mysql:mysqld -install 初始化mysql:mysqld --initialize 启动服 ...

  7. Anagrams问题

    #include<stdio.h> #include<string.h> int main() { int i; ],word2[]; //分别用于存储输入的两个单词 int ...

  8. 野指针、NULL指针和void*

    一.野指针 “野指针”不是NULL指针,是指向“垃圾”内存的指针. “野指针”的成因主要有三种: (1)指针变量没有被初始化.任何指针变量刚被创建时不会自动成为NULL指针,它的缺省值是随机的,它会乱 ...

  9. loadrunner 怎么能得到返回的http状态?

    loadrunner如何保存从服务器传回来的http头的信息? Action() { int HttpRetCode; web_url("www.hao123.com", &quo ...

  10. java程序执行时,JVM内存

    高淇 java 31集 类代码,static,常量池到方法区 (常量池会在类之间共享) 局部变量 到栈 对象到 堆 高淇 32集 增加一个computer类