NSData, NSURL, NSBundle

NSData:

创建方法:

+ (id)data;

+ (id)dataWithBytes:(constvoid *)bytes length:(NSUInteger)length;复制C数组所包含的数据来初始化NSData的数据

+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;直接利用C数组所包含的数据来初始化NSData对象。当该对象被执行malloc方法销毁自己时,程序会释放该C数组

+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;直接利用C数组所包含的数据来初始化NSData对象,只有当最后一个参数为YES,且该对象被执行malloc方法销毁自己时,程序才会释放该C数组

+ (id)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr;

+ (id)dataWithContentsOfURL:(NSURL *)url options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr;

+ (id)dataWithContentsOfFile:(NSString *)path;

+ (id)dataWithContentsOfURL:(NSURL *)url;

- (id)initWithBytes:(constvoid *)bytes length:(NSUInteger)length;

- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length;

- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b;

- (id)initWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr;

- (id)initWithContentsOfURL:(NSURL *)url options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr;

- (id)initWithContentsOfFile:(NSString *)path;

- (id)initWithContentsOfURL:(NSURL *)url;

- (id)initWithData:(NSData *)data;

+ (id)dataWithData:(NSData *)data;

一些重要常用的方法:

- (NSUInteger)length;

- (constvoid *)bytes;返回该NSData所包含的数据

- (NSString *)description;

- (void)getBytes:(void *)buffer length:(NSUInteger)length;获取NSData所包含的指定长度的数据

- (void)getBytes:(void *)buffer range:(NSRange)range;获取NSData所包含的指定范围的数据

- (BOOL)isEqualToData:(NSData *)other;

- (NSData *)subdataWithRange:(NSRange)range;获取NSData所包含的指定范围的数据组成的NSData对象

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;

- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically; 

- (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)writeOptionsMask error:(NSError **)errorPtr;

- (BOOL)writeToURL:(NSURL *)url options:(NSDataWritingOptions)writeOptionsMask error:(NSError **)errorPtr;

- (NSRange)rangeOfData:(NSData *)dataToFind options:(NSDataSearchOptions)mask range:(NSRange)searchRangeNS_AVAILABLE(10_6,4_0);



  1. #import <Foundation/Foundation.h>  
  2.   
  3. int main(int argc , charchar * argv[])  
  4. {  
  5.     @autoreleasepool{  
  6.         // 使用NSData读取指定URL对应的数据  
  7.         NSData* data = [NSData dataWithContentsOfURL:  
  8.             [NSURL URLWithString:@"http://www.crazyit.org/ethos.php"]];  
  9.         NSLog(@"%ld" , [data length]);  
  10.         // 定义一个长度为100的数组  
  11.         char buffer[100];  
  12.         // 将NSData指定范围的数据读入数组  
  13.         [data getBytes:buffer range: NSMakeRange(103100)];  
  14.         // 输出数组的内容  
  15.         NSLog(@"%s" , buffer);  
  16.         // 直接将NSData的数据用UTF-8的格式转换字符串  
  17.         NSString* content = [[NSString alloc] initWithData:data   
  18.             encoding:NSUTF8StringEncoding];  
  19.         NSLog(@"----------输出网页内容---------");  
  20.         NSLog(@"%@" , content);  
  21.     }  
  22. }  


  1. //复制文件
  2. #import <Foundation/Foundation.h>  
  3.   
  4. int main(int argc, const char * argv[])  
  5. {  
  6.   
  7.     @autoreleasepool {  
  8.           
  9.         NSFileManager * fm;  
  10.         NSData *fileData;  
  11.           
  12.         fm = [NSFileManager defaultManager];  
  13.           
  14.         //读取文件testfile.txt  
  15.         fileData = [fm contentsAtPath:@"testfile.txt"];  
  16.           
  17.         if(fileData == nil)  
  18.         {  
  19.             NSLog(@"File read failed!");  
  20.             return 1;  
  21.         }  
  22.           
  23.         //将数据写到 newfile.txt  (相当于拷贝文件)  
  24.         if ([fm createFileAtPath:@"newfile.txt" contents:fileData attributes:nil] == NO)  
  25.         {  
  26.             NSLog(@"Couldn't create the copy!");  
  27.             return 2;  
  28.         }  
  29.           
  30.         NSLog(@"File copy was successful!");  
  31.           
  32.         //读取拷贝后的文件 newfile.txt中的数据  
  33.         NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile.txt" encoding:NSUTF8StringEncoding error:nil]);  
  34.           
  35.          
  36.     
  37.     }  
  38.     return 0;  
  39. }  


类型转换

1,NSData 与 NSString
  NSData --> NSString
  NSString *aString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
  NSString --> NSData
  NSString *aString = @"1234";
  NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];

2,NSData 与 Byte
  NSData --> Byte
  NSString *testString = @"1234567890";
  NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];
  Byte *testByte = (Byte *)[testData bytes];
  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];

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);

4,NSData 与 NSMutableData
  NSData --> MSMutableData
  NSData *data=[[NSData alloc]init];
  NSMutableData *mdata=[[NSMutableData alloc]init];   
  mdata=[NSData dataWithData:data];

5,NSData合并为一个NSMutableData

- (NSString *)filePathWithName:(NSString *)filename
 {
         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
         NSString *documentsDirectory = [paths objectAtIndex:0];
         return [documentsDirectory stringByAppendingPathComponent:filename];
 }
 
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
     //音频文件路径
         NSString *mp3Path1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"];
         NSString *mp3Path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"];
         //音频数据
         NSData *sound1Data = [[NSData alloc] initWithContentsOfFile: mp3Path1];
         NSData *sound2Data = [[NSData alloc] initWithContentsOfFile: mp3Path2];
         //合并音频
         NSMutableData *sounds = [NSMutableData alloc];
         [sounds appendData:sound1Data];
         [sounds appendData:sound2Data];
         //保存音频
 
         NSLog(@"data length:%d", [sounds length]);
 
         [sounds writeToFile:[self filePathWithName:@"tmp.mp3"] atomically:YES];
         
         [window makeKeyAndVisible];
     
     return YES;
 }





NSURL
创建 NSURL *url = [NSURL URLWithString:@"..."];
读取 NSString *string = [NSString stringWithContentsOfUrl:url  encoding:NSASCIIStringEncoding  error:NULL];
dictionaryWithContentsOfURL; arrayWithContentsOfURL; dataWithContentsOfURL 





NSBundle

bundle是一个目录,其中包含了程序会使用到的资源. 这些资源包含了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in). 对应bundle,cocoa提供了类NSBundle.

我们的程序是一个bundle. 在Finder中,一个应用程序看上去和其他文件没有什么区别. 但是实际上它是一个包含了nib文件,编译代码,以及其他资源的目录. 我们把这个目录叫做程序的main bundle

bundle中的有些资源可以本地化.例如,对于foo.nib,我们可以有两个版本: 一个针对英语用户,一个针对法语用户. 在bundle中就会有两个子目录:English.lproj和French.lproj,我们把各自版本的foo.nib文件放到其中. 当程序需要加载foo.nib文件时,bundle会自动根据所设置的语言来加载. 我们会在16章再详细讨论本地化
通过使用下面的方法得到程序的main bundle
NSBundle *myBundle = [NSBundle mainBundle];
一般我们通过这种方法来得到bundle.如果你需要其他目录的资源,可以指定路径来取得bundle
NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];
一旦我们有了NSBundle 对象,那么就可以访问其中的资源了
// Extension is optional
NSString *path = [goodBundle pathForImageResource:@"Mom"];
NSImage *momPhoto = [[NSImage alloc] initWithContentsOfFile:path];
bundle中可以包含一个库. 如果我们从库得到一个class, bundle会连接库,并查找该类:
Class newClass = [goodBundle classNamed:@"Rover"];
id newInstance = [[newClass alloc] init];
如果不知到class名,也可以通过查找主要类来取得
Class aClass = [goodBundle principalClass];
id anInstance = [[aClass alloc] init];
可以看到, NSBundle有很多的用途.在这章中, NSBundle负责(在后台)加载nib文件. 我们也可以不通过NSWindowController来加载nib文件, 直接使用NSBundle:
BOOL successful = [NSBundle loadNibNamed:@"About" owner:someObject];
注意噢, 我们指定了一个对象someObject作为nib的File”s Owner

获取XML文件
NSString *filePath = [[NSBundle mainBundle] pathForResouse:@"re" ofType:@"xml"];
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];

获取属性列表 
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ViewControllers" ofType:@"plist"]];


详解

1、使用类方法创建一个NSBundler对象
+ (NSBundle *)mainBundle;
eg:[NSBundle mailBundle];
2、使用路径获取一个NSBundle 对象,这个路径应该是一个目录的全路径
+ (NSBundle *)bundleWithPath:(NSString *)path;
eg:  
NSString *path = [mailBundle resourcePath];
   NSBundle *language = [NSBundle bundleWithPath:path];
3、使用路径初始化一个NSBundle
- (id)initWithPath:(NSString *)path;


4、使用一个url 创建并初始化一个NSBundle对象(这是一个类方法)
注:这里的url 是一个特殊的 文件url路径
+ (NSBundle *)bundleWithURL:(NSURL *)url
5、使用一个url 初始化一个NSBundle对象
注:这里的url 是一个特殊的 文件url路径
- (id)initWithURL:(NSURL *)url
6、根据一个特殊的class 获取NSBundle
+ (NSBundle *)bundleForClass:(Class)aClass;
eg:根据当前的class 获取一个NSBundle // 获取当前类的NSBundle
NSBundle *bud = [NSBundle bundleForClass:[self class]];
NSLog(@"bud==%@",bud);
输出结果如下:
NSBundle </Users/ctrip1/Library/Application Support/iPhone Simulator/6.1/Applications/2F3DA58F-5CF9-48A2-ADB2-C923A29B519E/IOS_Example_NSBundle.app>
7、获取特定名称的bundle
+ (NSBundle *)bundleWithIdentifier:(NSString *)identifier;
8、使用NSBundle 获取所有的bundle信息(由于ios安全沙盒的限制,所有的获取的资源,是应用程序的资源)
注:官方标注,获取所有的非framework 的bundle;
+ (NSArray *)allBundles;
eg:
NSArray *array = [NSBundle allBundles];
NSLog(@"array===%@",array);
打印的结果如下:
array===(
     "NSBundle </Users/ctrip1/Library/Application Support/iPhone Simulator/6.1/Applications/2F3DA58F-5CF9-48A2-ADB2-C923A29B519E/IOS_Example_NSBundle.app> (loaded)"
)
9、获取应用程序加载的所有framework的资源,
+ (NSArray *)allFrameworks;
eg:
NSArray *array = [NSBundle allFrameworks];
NSLog(@"%@",array);


10、判断bundle 加载,(按照官方文档,You don’t need to load a bundle’s executable code to search the bundle’s resources.我们不需要调用这个方法,)
- (BOOL)load;


11、判断bundle 加载
- (BOOL)isLoaded;


12、判断bundle 加载
- (BOOL)unload;


13、加载资源,如果有错误的话,会放置错误信息
- (BOOL)preflightAndReturnError:(NSError **)error
- (BOOL)loadAndReturnError:(NSError **)error
14、获取bundle 类实例的 url 
- (NSURL *)bundleURL


15、获取bundle 类实例的 resourceUrl 资源
- (NSURL *)resourceURL


16、获取bundle 类实例的 可执行的URL 
- (NSURL *)executableURL


17、(Returns the file URL of the executable with the specified name in the receiver’s bundle.返回一个,文件的URL,使用一个特殊的名称)
- (NSURL *)URLForAuxiliaryExecutable:(NSString *)executableName


18、获取当前NSBundle实例的 URL 资源
- (NSURL *)privateFrameworksURL
19、获取共享的frameworkdURL
- (NSURL *)sharedFrameworksURL
20、 获取支持的Bundle的Url
- (NSURL *)sharedSupportURL
21、获取添加插件的URL 
- (NSURL *)builtInPlugInsURL
// 已经不能使用,
- (NSURL *)appStoreReceiptURL
22、 获取bundle 的path 路径
- (NSString *)bundlePath;


23、获取bundle 的资源路径字符串
- (NSString *)resourcePath;


24、获取bundle 可执行文件路径
- (NSString *)executablePath;


25、获取bundle 辅助的path
- (NSString *)pathForAuxiliaryExecutable:(NSString *)executableName;


26、获取私有的路径框架
- (NSString *)privateFrameworksPath;
27、获取共享的framework path 路径
- (NSString *)sharedFrameworksPath;


28、获取共享的路径
- (NSString *)sharedSupportPath;


29、获取插件的路径
- (NSString *)builtInPlugInsPath;


// 已经废弃,不能调用
+ (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath inBundleWithURL:(NSURL *)bundleURL
// 已经废弃
+ (NSArray *)URLsForResourcesWithExtension:(NSString *)ext subdirectory:(NSString *)subpath inBundleWithURL:(NSURL *)bundleURL


30、使用bundle 创建一个资源文件的URL
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext
eg:
NSURL* URL=[[NSBundle mainBundle] URLForResource:fileName withExtension:@"png"];
31、(官方描述如下:Returns the file URL for the resource file identified by the specified name and extension and residing in a given bundle directory.
使用资源文件的名称以及扩展名,还有子路径)
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath


32、(官方描述:
Returns the file URL for the resource identified by the specified name and file extension, 
located in the specified bundle subdirectory, and limited to global resources and those associated with the specified localization.)
同上一个方法,不同的是添加了本地资源文件的信息
- (NSURL *)URLForResource:(NSString *)name withExtension:(NSString *)ext subdirectory:(NSString *)subpath localization:(NSString *)localizationName


33、根据文件的后缀名称和子目录,获取一个NSURL 的数组
- (NSArray *)URLsForResourcesWithExtension:(NSString *)ext subdirectory:(NSString *)subpath
34、同上面的方法,添加了本地化的一个资源文件
- (NSArray *)URLsForResourcesWithExtension:(NSString *)ext subdirectory:(NSString *)subpath localization:(NSString *)localizationName


35、根据资源文件的名称,或者是文件的后缀名称以及目录的路径,获取 path
+ (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)bundlePath;


36、根据文件的扩展名,以及资源的路径,获取一个数组
+ (NSArray *)pathsForResourcesOfType:(NSString *)ext inDirectory:(NSString *)bundlePath;


37、根据文件的名称和扩展名获取 path 名称
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext;


37、根据文件的名称和扩展名获取 path 名称
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath;


37、根据文件的名称和扩展名获取 path 名称
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)ext inDirectory:(NSString *)subpath forLocalization:(NSString *)localizationName;


38、根据文件的扩展名和子目录获取一个资源文件的数组
- (NSArray *)pathsForResourcesOfType:(NSString *)ext inDirectory:(NSString *)subpath;


39、同上,添加了资源文件的一个路径
- (NSArray *)pathsForResourcesOfType:(NSString *)ext inDirectory:(NSString *)subpath forLocalization:(NSString *)localizationName;
40、方法调用解释如下
- (NSString *)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName NS_FORMAT_ARGUMENT(1);

41、返回本地化资源的NSDictionary 对象
- (NSDictionary *)localizedInfoDictionary;


42、根据key 值获取本地化资源对象的值
- (id)objectForInfoDictionaryKey:(NSString *)key;


43、(官方描述:Returns the Class object for the specified name.根据类名字符串获取一个类对象)
- (Class)classNamed:(NSString *)className;
44、返回主要的类
- (Class)principalClass;
45、返回本地化资源的列表
- (NSArray *)localizations;
46、本地化的语言列表
- (NSArray *)preferredLocalizations;
47、使用创建的类获取本地化语言
- (NSString *)developmentLocalization;
48、(官方描述 Returns one or more localizations from the specified list that a bundle object would use to locate resources for the current user.)
+ (NSArray *)preferredLocalizationsFromArray:(NSArray *)localizationsArray;
+ (NSArray *)preferredLocalizationsFromArray:(NSArray *)localizationsArray forPreferences:(NSArray *)preferencesArray;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值