Foundation框架和文件操作

NSString 

--实例化方法-------------- 

NSString *str = [[NSString alloc] init]; 

NSString *str = [[[NSString alloc] init]autorelease];   

注意:在NSString中存在自己的实例化和初始化的方法 比如: 

NSString *str1 = [NSString stringWithCString:"newString" enconding: NSACIIStringEncoding]; 

NSString *str2 = [NSString alloc]initWithCString:"new String" enconding: NSACIIStringEncoding]; 

str1和str2两个对象是同样的。

--NSStringEncoding 中经常使用的字符编码---------------- 

     NSASCIIStringEncoding 

     NSUTF8StringEncoding 

     NSUnicodeStringEncoding 

--NSString创建实例---------------- 

带“@”符号的方法仅仅能定义含有英文和数字的NSString实例,比如: 

NSString *str = "Hello money~"; 

--生成含有中文的NSString方法------------- 

//此方法自己主动释放内存 

+ (id)stringWithCString:(const char*)cStringencoding:(NSStringEncoding)encoding; 

//进行alloc后进行初始化 

- (id)initWithCString:(const char*)cStringencoding:(NSStringEncoding)encoding; 

比如: 

NSString *string = [NSStringstringWithCString:"您好" encoding:NSUTF8StringEncoding]; 

NSString *string = [[NSString alloc]initWithCString:"您好" encoding:NSUTF8StringEncoding]; 

--使用格式创建字符串------------- 

+ (id)stringWithFormat:(NSString *)format... 

- (id)initWithFormat:(NSString *)format... 

比如: 

NSString*str = "hello"; 

NSString*string = [NSString stringWithFormat:@"%@ world",str]; 

NSLog(string);结果:helloworld 

能够用于描写叙述全路径,

--经常使用的替换符-------------- 

%@ NSString实例 

%d,%D,%i 整数 

%u,%U 无符号整数 

%x 将无符号整数以十六进制小写字母显示 

%X 将无符号整数以十六进制大写字母显示 

%f 小数 

%c 字符 

%s C语言字符串 

%% 显示%字符本身 

-------------------------- 

NSRange 

--NSRange的定义 

typedef struct _NSRange 

     unsigned int location; 

     unsigned int length; 

}NSRange; 

NSMakeRange函数 

--这个函数比較特殊 返回一个NSRange的对象。

NSMakeRanger(unsigned int location,unsigned int length); 

比如: 

NSRange range = NSMakeRanger(0,5); 

NSLog(@"location is %d,length is%d",range.location,range.length); 

--------------------------- 

计算字符串长度 

- (unsigned int)length; 

--------------------------- 

字符串连接。插入和删除 

1、连接 

- (NSString *)stringByAppendingString:(NSString *)string; 

- (NSString *)stringByAppendingFormat:(NSString *)format...; 

比如: 

     NSString *str1 =@"hello"; 

     NSString *str2 =@"world"; 

     NSString *str3 = [str1stringByAppendingString:str2]; 

     NSString *str4 = [str2stringByAppendingFormat:@"%d...%d",10,20]; 

     str4 --> world 10...20 

    

     ----------------- 

     NSMutableString的生成 

     NSString   +(id)string;  //生成空字符串的实例 

     +(id)stringWithString:(NSString *)string;     //带自己主动释放内存 

     - (id)initWithString:(NSString*)string; 

     比如: 

     NSMutableString *string =[NSMutableString stringWithString:@"hello"]; 

2、追加字符串 

     NSMutableString 

     + (void)appendString:(NSString*)string; 

     - (void)appendFormat:(NSString*)format...; 

     比如: 

     NSMutableString string = [NSMutableStringstring]; 

     [stringappendString:@"hello"]; 

     [stringappendString:@"money"]; 

     [string appendString:@" andworld"]; 

3、插入字符串 

     NSMutableString 

     + (void)insertString:(NSString *)stringatIndex:(unsigned)index; 

     从index位置插入字符串 

     比如: 

     NSMutableString *string =[NSMutableString stringWithString:@"Mac X"]; 

     [string insertString:@"OS"atIndex:4]; 

     string --> Mac OS X 

4、删除字符串 

     NSMutableString 

     +(void)deleteCharactersInRange:(NSRange)range; 

     比如: 

     NSMutableString *string =[NSMutableString stringWithString:@"Mac os"]; 

     [stringdeleteCharactersInRange:NSMakeRanger(0,1)]; 

     NSLog(string); 

     string -->ac os; 

5、字符串比較 

     NSString 

     - (BOOL)isEqualToString:(NSString*)string; 

6、比較前置串和后置串 

     NSString 

     - (BOOL)hasPrefix:(NSString*)string; 

     - (BOOL)hasSuffix:(NSString*)string; 

     比如: 

     NSString *str1 = @"MacOS"; 

     NSString *str2 = @"MacPro"; 

     BOOL flag; 

     flag = [str1hasPrefix:@"Mac"];  YES 

     flag = [str2hasSuffix:@"OS"];      NO 

7、字符串检索 

     NSString 

     //假设找到就返回范围,否则NSRange的location项被设置为NSNotFound 

     - (NSRange)rangeOfString:(NSString*)subString; 

     - (NSRange)rangeOfString:(NSString*)subString option:(unsigned)mask; 

     - (NSRange)rangeOfString:(NSString*)subString option:(unsigned)mask     range:(NSRange)range;                                                                                        

     -----mask经常使用选项列表 

    NSCaseInsensitiveSearch          不区分字母大写和小写 

    NSLiteralSearch          对字符串进行字节单位的比較。一般可提高检索速度 

    NSBackwardsSearch     从范围的末尾開始检索 

    NSAnchoredSearch     仅检索制定范围的前部。

忽略字符串中间的检索字符 

     比如: 

     NSString *string = @"helloworld"; 

     NSRange range = [stringrangeOfString:@"he"]; 

     if(range.location != NSNotFound) 

     { 

         NSLog(@" location=%d,length=%d",range.location,range.length); 

     } 

8、截取字符串 

     NSString 

     - (NSString*)substringToIndex:(unsigned)index;     //返回字符串开头至index位的字符串 不包括索引位 

     - (NSString*)substringFromIndex:(unsigned)index; //返回字符串第index位至末尾的字符串 包括索引位 

     - (NSString*)substringWithRange:(NSRange)range;     //返回字符串中范围range内的字符串 包括索引位 

     比如: 

     NSString *string = [stringsubstringWithRange:NSMakeRange(5,2)]; 

9、读取文本文件 

     NSString 

     +(id)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding*)enc error:(NSError **)error     //自己主动释放内存 

    

     - (id)initWithContentsOfFile:(NSString*)path encoding:(NSStringEncoding)enc error:(NSError **)error 

    

+dictionaryWithContentsOfFile

+dictionaryWithContentsOfURL

     比如: 

     NSString *string = [NSStringstringWithContentsOfFile:@"/user/test/yw.txt"encoding:NSUTF8StringEncoding error:&error]; 

     if(string){} 

10、输出文本文件 

     NSString 

     - (BOOL)writeToFile:(NSString *)pathatomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError**)error 

     //參数atomically 临时将文件保存到辅助文件里 

    //扩展路径 

    NSString *Path =@"~/NSData.txt"; 

    NSString *absolutePath = [PathstringByExpandingTildeInPath]; 

   NSLog(@"absolutePath:%@",absolutePath); 

    NSLog(@"Path:%@",[absolutePathstringByAbbreviatingWithTildeInPath]); 

    //文件扩展名 

    NSString *Path =@"~/NSData.txt"; 

    NSLog(@"Extension:%@",[PathpathExtension]);

        之前在初始化一个类的时候:TestViewController*viewcontroller=[[TestViewControlleralloc]initWithNibName:@"TestViewController" bundle:[NSBundlemainBundle]];不是非常明确:[NSBundle mainBundle]的意思。后来查阅资料后知道了它的作用,例如以下:

        bundle是一个文件夹,当中包括了程序会使用到的资源. 这些资源包括了如图像,声音,编译好的代码,nib文件(用户也会把bundle称为plug-in).相应bundle,cocoa提供了类NSBundle.我们的程序是一个bundle. 在Finder中,一个应用程序看上去和其它文件没有什么差别. 可是实际上它是一个包括了nib文件,编译代码,以及其它资源的文件夹. 我们把这个文件夹叫做程序的main bundle。

通过使用以下的方法得到程序的main bundle

NSBundle *myBundle = [NSBundle mainBundle];

一般我们通过这样的方法来得到bundle.假设你须要其它文件夹的资源,能够指定路径来取得bundle

NSBundle *goodBundle;

goodBundle = [NSBundlebundleWithPath:@"~/.myApp/Good.bundle"];

一旦我们有了NSBundle 对象,那么就能够訪问当中的资源了

NSBundle束,是一种特定的文件类型,当中的内容遵循特定的结构。

NSBundle的一个主要作用是 获取Resources目录中的资源。

       在编程中使用[NSDatadataWithContentOfFile:@"foo"]的时候。总是无法读取正确的文件内容。而使用[NSData dataWithContentOfFile:[[NSBundle mainBundle]pathForResource:@”foo” ofType:@”"]的时候就能够。

由于当使用相对路径的时候。事实上他相对的当前文件夹并非程序执行的文件夹,而是“/”。仅仅有使用[NSBundlemainBundle]来生成的路径才是文件真正的路径。

在此记录一下:在以后的开发中不直接使用不论什么相对路径,而是使用经过计算以后的绝对路径。

一.获取图片

  1.   NSString *path = [[NSBuddle mainBuddle]pathForResource:@"resourceName" oftype@"resourceType"];

       UIImage *image =[[UIImage imageWithContentsOfFile:path];

  2.   UIImage *image = [UIImageimageNamed:@"imageName"];

二.获取plist文件

  NSArray *array =[[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"name"ofType:@"plist"]];

  NSDictionary*dict=[arrayobjectAtIndex:index];//将plist文件里的内容转换成字典

  

NSFileManager,defaultManager()返回一个文件管理器的单例(多线程下不安全)。

init(),在多线程编程中应尽量使用init()。

代理方法:-fileManager:shouldRemoveItemAtPath和-fileManager:shouldRemoveItemAtURL在移除操作之前被调用。

-removeItemAtPath:error:删除位于指定路径的文件、连接、文件夹(及其全部子文件夹、文件)。

-removeItemAtURL:error:同上。

-contentOfDirectoryAtPath:查找全部位于给定路径的子路径和文件。返回值为一个数组,当中包括了NSString对象。

查找仅仅在当前文件夹进行。不会进入下一层文件夹。

-subpathsAtPath:查找给定路径下的全部子路径。深度查找,不限于当前层,也会查找package的内容。

-fileExistsAtPath:推断文件是否位于一个路径以下。

-isReadableFileAtPath:查询文件的可读性

-isWritableFileAtPath:可写性

-isExecutableFileAtPath:查询文件的可运行性

-isDeletableFileAtPath:可删除性

3-NSString的路径功能

-pathWithComponent:參数是一堆components构成的数组,返回的路径是由这些components连接而成的路径字符串,相邻components之间用/隔开。

-pathComponents:返回一个数组,包括路径中的components。

-fileSystemRepresentation:返回C字符串

-isAbsolutePath:推断是否为绝对路径

-pathExtension:返回文件的扩展名。没有的就返回空字符串

-stringByAppendingPathComponents :向现有路径加入一个component。斜杠/会被自己主动加上

-stringByAppendingPathExtension:向现有路径加上文件的扩展名

-stringByDeletingLastPathComponent:移除最后一个路径component

-stringByDeletingPathExtension:删除路径扩展名

-stringByAppendingPaths:參数为一个数组,此方法将数组中的字符串对象作为路径一次加入到源字符串后面。

样例:

NSString *homePath = NSHomeDirectory();

NSString *docPath = [homePathstringByAppendingFormat:@"/Documents"];

    

1- 音频

[1] 音乐往往是存储在iPod曲库(注意位置)中的,能够通过媒体选择器(media picker)或者媒体查询(media query)读取,然后用音乐播放器MPMusicPlayerController播放。

MPMusicPlayerController *musicPlayer =[MPMusicPlayerController applicationMusicPlayer];

[musicPlayer setShufleMode: MPMusicShuffleModeSongs];

[musicPlayer setRepeatMode: MPMusicRepeatModeAll];

[musicPlayer setQueueWithQuery:[MPMediaQuery songsQuery];

[musicPlayer play];

applicationMusicPlayer返回的播放器。在你的应用中播放音乐。

它不会影响到iPod播放器,也不能从iPod播放器重获取信息。

iPodMusicPlayer返回的是iPod播放器。在你推出应用后,全部的设置都会影响到之后设备上的iPod播放器。

获得音乐播放器后,须要为它设置一个播放队列。能够用setQueueWithQuery:放方法。通过媒体查询MPMediaQuery来设置播放队列,也能够用setQueueWithItemCollection:方法,通过MPMdiaItemCollection来设置播放队列。

反复模式repeatMode能够设置为不反复、反复当前曲目、或整个播放列表;乱序播放shuffleMode能够设置为不乱序、乱序播放曲目或乱序播放专辑;音量volume的设置与音频播放器一样。

skipToNextItem跳到下一首。skipToPreviousItem跳到上一首。skipToBegin跳到第一首。

相应的宏都是以MPMusic开头。

[2] 利用系统声音服务来播放短暂音效(时长30秒以内),并震动:

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

播放指定音效:

NSURL *fileURL = [NSURL fileURLWithPath: pathisDirectory: NO];

// 创建音效ID

SystemSoundID soundID;

AudioServiceCreateSystemSoundID((CFURLRef) fileURL,&soundID);

// 播放声音

AudioServicesPlaySystemSound(soundID);

[3] 音频播放器

没有时长限制

NSURL *fileURL = [NSURL fileURLWithPath: pathisDirectory: NO];

// 用URL来初始化音频播放器-播放的不是iPod曲库中的音乐

AVAudioPlayer* player = [AVAudioPlayeralloc] initWithContentsOfURL: fileURL error: NO];

// 准备播放

[player prepareToPlay];

// 设置代理

[player setDelegate: self];

方法:play、pause、stop。能够通过playing属性查询播放器是否正在播放其中,能够通过volume属性来改动和查询播放器的播放增益(从0.0到1.0),可通过setting属性查询播放器其它设置。

duration表示音频的时间长度,currentTime表示当前播放到的时间。

播放结束后能够通过代理方法audioPlayerDidFinishPlaying:来处理播放后设置。

2- 视频

视频播放能够採用网页视图(UIWebView)进行嵌入式播放(能播放YouTube视频)。或者採用电影播放器(MPMoviePlayerController)进行播放。

[1] 电影播放器

MPMoviePlayerController *player = [MPMoviePlayerControlleralloc]initWithContentURL: url];

// 设置播放器的大小,并将其增加视图中

[player.view setFrame: rectFrame];

[self.view addSubView: player.view];

播放器的背景视图backgroundView。

全屏[player setFullscreen: YES animated: YES];

播放还有一个影片[player setContentURL: newURL];

[playerrequestThumbnailImagesAtTimes:arrayTimestimeOption:MPMovieTimeOptionNearestKeyFrame]; // 表示播放器不会在你所指定的时间去截取预览。而是在绝对时间的附近几帧中寻找效果最好的帧做为预览。

scalingMode规定了影片的缩放模式。

initialPlaybackTime用来控制视频開始播放的时间,单位是秒。

假设视频源在网络上,那么须要正确设置server端的mimeType

  

第一种 使用for循环加 count 方法遍历 

?

1

2

3

4

5

int i = 0;

for(i = 0; i < [array count]; i++)

{

    [array objectAtIndex:i]

}

另外一种 使用for in方式遍历 

?

1

2

3

4

for(NSString *str in array)

{

    操作

}

第三种 使用枚举方式遍历 

?

1

2

3

4

5

6

7

NSEnumerator *enumer;

emumer = [array objectEnumerator];

NSString *str;

while(str = [enumer nextObject])

{

    操作

}

                                       

原文地址:https://www.cnblogs.com/claireyuancy/p/7078013.html