
因为Cocoa的数据类型之间的互转在实际程序中应用很广泛,因此在此记录一下常用的几个互转。
1 NSData和Nsstring之间互转:
123456789 | /* Nsstring to NSData */ Nsstring *theString = @"This is a string"; NSData *theStringData = [theString dataUsingEnCoding:NSUTF8StringEnCoding]; NSLog(@"%@\n%@", theString,210)!important">theStringData); /* NSData to Nsstring */ theStringFromData = [[Nsstring alloc] initWithData:theStringData enCoding:@"%@",210)!important">theStringFromData); [theStringFromData release]; |
这里用NSUTF8StringEnCoding作为例子,实际可以使用更多其它的编码类型,详情可以参考文档。
2 从某个路径(Nsstring)加载图片
imagePath = [[NSBundle mainBundle] pathForImageResource:@"some_image"]; NSImage *theImage = [[NSImage initWithContentsOffile:imagePath]; //[self.imageWell setimage:theImage]; [theImage 除了可以从Nsstring加载图片,也可以从NSURL加载。方法类似。3
9101112131415NSImage之间互转:
/* NSImage to NSData (TIFF) */ someData = [NSData dataWithContentsOffile:imagePath]; someImage = [[someData]; dataFromImage = [someImage TIFFRepresentation]; NSMutableString *homeDir = [[NSMutableString initWithString:NSHomeDirectory()]; [dataFromImage writetofile:[homeDir stringByAppendingPathComponent:@"Desktop/image.tiff"] atomically:NO]; /* NSImage to NSData (Any Format,use png as example) */ //NSBitmAPImageRep *bmprep = [NSBitmAPImageRep imageRepWithData:dataFromImage]; // TIFF representation data NSBitmAPImageRep *bmprep = [NSBitmAPImageRep imageRepWithData:someData]; // PNG data from file NSDictionary *imageProperty = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithfloat:0.0],210)!important">NSImageCompressionFactor, nil]; otherTypeImageData = [bmprep representationUsingType:NSPNGfileType propertIEs:imageProperty]; [otherTypeImageData @"Desktop/image.png"] NO]; [homeDir release]; [NSImage之间互转实际上相当复杂。这里使用了NSBitmAPImageRep作为中间对象来完成对各种图片类型的支持(主要包括TIFF,JPEG,GIF和PNG)。特别是imageProperty这个NSDictionary,在实际使用中需要参考文档进行赋值。4
8NSURL和`Nsstring之间互转:
/* Nsstring to NSURL */ Google = @"http://Google.com"; NSURL *GoogleURL = [[NSURL Google]; GoogleURL); /* NSURL to Nsstring */ @"%@,%@", [GoogleURL relativeString],210)!important">absoluteString]); [ 从Nsstring到NSURL没什么说的;从NSURL到Nsstring,有两个方法,一个是绝对路径,一个是相对路径。对于本地文件的路径,这两个方法是有区别的;而对于网页等远程路径,这两个方法返回的值相同。5
7CGImage转NSImage
/* CGImage to NSImage */ bitmapRep = [[NSBitmAPImageRep initWithCGImage:cgImage]; image = [[alloc] init]; [image addRepresentation:bitmapRep]; [bitmapRep imageVIEw setimage:image]; [image release];
以上是内存溢出为你收集整理的Cocoa的几种内置数据类型之间的互转全部内容,希望文章能够帮你解决Cocoa的几种内置数据类型之间的互转所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)