[Objective-C语言教程]基础框架(34)
如果您参考Apple文档,应该会看到Foundation框架的详细信息,如下所示。
Foundation框架定义了Objective-C类的基础层。 除了提供一组有用的原始对象类之外,它还引入了几个定义Objective-C语言未涵盖的功能的范例。 Foundation框架的设计考虑了这些目标 -
- 提供一小组基本实用程序类。
- 通过为解除分配等事项引入一致的约定,使软件开发更容易。
- 支持Unicode字符串,对象持久性和对象分发。
- 提供一定程度的操作系统独立性以增强可移植性。
该框架由NeXTStep 开发,后者被Apple收购,这些基础类成为Mac OS X和iOS的一部分。 由NeXTStep开发,它的类前缀为“NS”。
在所有示例程序中都使用了Foundation框架,在使用Objective-C语言开发应用程序时,使用Foundation框架几乎是必须的。
通常,我们使用#import <Foundation/NSString.h>之类的东西来导入Objective-C类,但是为了避免手写导入的类太多,使用#import <Foundation/Foundation.h>导入即可。
NSObject是所有对象的基类,包括基础工具包类。 它提供了内存管理的方法。 它还提供了运行时系统的基本接口以及表现为Objective-C对象的能力。它没有任何基类,是所有类的根。
基础类的功能
| 编号 | 功能 | 描述 | 
|---|---|---|
| 1 | 数据存储 | NSArray,NSDictionary和NSSet为Objective-C任何类的对象提供存储。 | 
| 2 | 文本和字符串 | NSCharacterSet表示NSString和NSScanner类使用的各种字符分组。NSString类表示文本字符串,并提供搜索,组合和比较字符串的方法。NSScanner对象用于扫描NSString对象中的数字和单词。 | 
| 3 | 日期和时间 | NSDate,NSTimeZone和NSCalendar类存储时间和日期并表示日历信息。它们提供了计算日期和时间差异的方法。它们与NSLocale一起提供了以多种格式显示日期和时间以及根据世界中的位置调整时间和日期的方法。 | 
| 4 | 异常处理 | 异常处理用于处理意外情况,它在Objective-C中提供 NSException类对象。 | 
| 5 | 文件处理 | 文件处理是在 NSFileManager类的帮助下完成的。 | 
| 6 | URL加载系统 | 一组提供对常见Internet协议访问的类和协议。 | 
1、数据存储
数据存储及检索是任何程序中最重要的一个操作。 在Objective-C中,通常不会依赖链表等结构,因为它会使工作变得复杂。一般使用像NSArray,NSSet,NSDictionary及其可变形式的集合。
1.1 NSArray和NSMutableArray
NSArray用于保存不可变对象数组,NSMutableArray用于保存可变对象数组。Mutablility有助于在运行时更改预分配数组中的数组,但如果使用NSArray,只替换现有数组,并且不能更改现有数组的内容。
NSArray的重要方法如下 -
- alloc/initWithObjects− 用于使用对象初始化数组。
- objectAtIndex− 返回指定索引处的对象。
- count− 返回对象数量。
NSMutableArray继承自NSArray,因此NSArray的所有实例方法都可在NSMutableArray中使用
NSMutableArray的重要方法如下 -
- removeAllObjects− 清空数组。
- addObject− 在数组的末尾插入给定对象。
- removeObjectAtIndex− 这用于删除- objectAt指定的索引处的对象。
- exchangeObjectAtIndex:withObjectAtIndex− 在给定索引处交换数组中的对象。
- replaceObjectAtIndex:withObject− 用Object替换索引处的对象。
需要记住,上面的列表只是常用的方法,可以到XCode中查看各个类,以了解这些类中的更多方法。一个简单的例子如下所示 -
1 #import <Foundation/Foundation.h> 2 3 int main() { 4 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 5 NSArray *array = [[NSArray alloc] 6 initWithObjects:@"string1", @"string2",@"string3",nil]; 7 NSString *string1 = [array objectAtIndex:0]; 8 NSLog(@"The object in array at Index 0 is %@",string1); 9 10 NSMutableArray *mutableArray = [[NSMutableArray alloc]init]; 11 [mutableArray addObject: @"string"]; 12 string1 = [mutableArray objectAtIndex:0]; 13 NSLog(@"The object in mutableArray at Index 0 is %@",string1); 14 15 [pool drain]; 16 return 0; 17 }
执行上面示例代码,得到以下结果:
1 2018-11-16 04:06:24.683 main[69957] The object in array at Index 0 is string1 2 2018-11-16 04:06:24.684 main[69957] The object in mutableArray at Index 0 is string
在上面的程序中,可以看到NSMutableArray和NSArray之间的简单区别,并在可变数组中分配后插入一个字符串。
1.2 NSDictionary和NSMutableDictionary
NSDictionary用于保存对象的不可变字典,NSMutableDictionary用于保存对象的可变字典。
NSDictionary的一些重要方法如下 -
- alloc/initWithObjectsAndKeys− 使用指定的值和键集构造的条目初始化新分配的字典。
- valueForKey− 返回与给定键关联的值。
- count− 返回字典中的项目数。
NSMutableDictionary继承自NSDictionary,因此NSDictionary的所有实例方法都可以在NSMutableDictionary中使用。NSMutableDictionary的重要方法如下 -
- removeAllObjects- 清空字典的条目。
- removeObjectForKey- 从字典中删除给定键及其关联值。
- setValue:forKey- 将给定的键值对添加到字典中。
下面是字典的一个简单示例 -
1 #import <Foundation/Foundation.h> 2 3 int main() { 4 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 5 NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: 6 @"string1",@"key1", @"string2",@"key2",@"string3",@"key3",nil]; 7 NSString *string1 = [dictionary objectForKey:@"key1"]; 8 NSLog(@"The object for key, key1 in dictionary is %@",string1); 9 10 NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc]init]; 11 [mutableDictionary setValue:@"string" forKey:@"key1"]; 12 string1 = [mutableDictionary objectForKey:@"key1"]; 13 NSLog(@"The object for key, key1 in mutableDictionary is %@",string1); 14 15 [pool drain]; 16 return 0; 17 }
执行上面示例代码,得到以下结果 -
1 2018-11-16 04:11:49.006 main[100527] The object for key, key1 in dictionary is string1 2 2018-11-16 04:11:49.007 main[100527] The object for key, key1 in mutableDictionary is string
1.3 NSSet和NSMutableSet
NSSet用于保存不可变的一组不同的对象,NSMutableDictionary用于保存一组可变的不同对象。NSSet的重要方法如下 -
- alloc/initWithObjects- 使用从指定的对象列表中获取的成员初始化新分配的集合。
- allObjects- 返回包含集合成员的数组,如果集合没有成员,则返回空数组。
- count- 返回集合中的成员数量。
NSMutableSet继承自NSSet类,因此NSSet的所有实例方法都可以在NSMutableSet中使用。
NSMutableSet的一些重要方法如下 -
- removeAllObjects− 清空集合的所有成员。
- addObject− 如果给定对象尚未成为成员,则将该对象添加到该集合中。
- removeObject− 从集合中删除给定对象。
集合的简单示例如下所示 -
1 #import <Foundation/Foundation.h> 2 3 int main() { 4 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 5 NSSet *set = [[NSSet alloc] 6 initWithObjects:@"yii", @"bai",@".com",nil]; 7 NSArray *setArray = [set allObjects]; 8 NSLog(@"The objects in set are %@",setArray); 9 10 NSMutableSet *mutableSet = [[NSMutableSet alloc]init]; 11 [mutableSet addObject:@"yiibai"]; 12 setArray = [mutableSet allObjects]; 13 NSLog(@"The objects in mutableSet are %@",setArray); 14 15 [pool drain]; 16 return 0; 17 }
执行上面示例代码,得到以下结果 -
1 2018-11-16 04:46:06.667 main[196448] The objects in set are (".com", bai, yii) 2 2018-11-16 04:46:06.669 main[196448] The objects in mutableSet are (yiibai)
2、文本和字符串
NSString是最常用的类,用于存储字符串和文本。 如果想了解更多有关NSString的信息,请参阅Objective-C字符串中的NSString部分。
如前所述,NSCharacterSet表示NSString和NSScanner类使用的各种字符分组。
1. NSCharacterSet
以下是NSCharacterSet中可用的方法集,它们表示各种字符集。
- alphanumericCharacterSet- 返回包含“字母”,“标记”和“数字”类别中的字符的字符集。
- capitalizedLetterCharacterSet- 返回包含首字母大写字母类别中字符的字符集。
- characterSetWithCharactersInString- 返回包含给定字符串中字符的字符集。
- characterSetWithRange- 返回包含给定范围内具有- Unicode值的字符的字符集。
- illegalCharacterSet- 返回一个字符集,其中包含非字符类别中的值或尚未在- Unicode标准的- 3.2版中定义的值。
- letterCharacterSet- 返回包含- Letters和- Marks类别中字符的字符集。
- lowercaseLetterCharacterSet- 返回包含“小写字母”类别中字符的字符集。
- newlineCharacterSet- 返回包含换行符的字符集。
- punctuationCharacterSet- 返回包含标点符号类别中字符的字符集。
- symbolCharacterSet- 返回包含符号类别中字符的字符集。
- uppercaseLetterCharacterSet- 返回包含大写字母和标题字母类别中字符的字符集。
- whitespaceAndNewlineCharacterSet- 返回包含Unicode一般类别- Z*,- U000A~U000D和- U0085的字符集。
- whitespaceCharacterSet- 返回仅包含内嵌空白字符空间(- U+0020)和制表符(- U+0009)的字符集。
示例代码如下所示 -
1 #import <Foundation/Foundation.h> 2 3 int main() { 4 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 5 NSString *string = @"....strengthen.com....."; 6 NSLog(@"Initial String :%@", string); 7 8 NSCharacterSet *characterset = [NSCharacterSet punctuationCharacterSet]; 9 string = [string stringByTrimmingCharactersInSet:characterset]; 10 NSLog(@"Final String :%@", string); 11 12 [pool drain]; 13 return 0; 14 }
执行上面示例代码,得到以下结果 -
1 2018-11-16 04:51:42.927 main[153479] Initial String :....strengthen.com..... 2 2018-11-16 04:51:42.929 main[153479] Final String :strengthen.com.....
可以在上面的程序中看到,修剪了给定字符串两边的标点符号。这只是使用NSCharacterSet的一个例子。
3、日期和时间
在Objective-C中,NSDate和NSDateFormatter类用于提供日期和时间的功能。NSDateFormatter是一个帮助程序类,可以很容易地将NSDate转换为NSString,反之亦然。
显示将NSDate转换为NSString并返回NSDate的简单示例如下所示 -
1 #import <Foundation/Foundation.h> 2 3 int main() { 4 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 5 NSDate *date= [NSDate date]; 6 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 7 [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 8 9 NSString *dateString = [dateFormatter stringFromDate:date]; 10 NSLog(@"Current date is %@",dateString); 11 NSDate *newDate = [dateFormatter dateFromString:dateString]; 12 NSLog(@"NewDate: %@",newDate); 13 14 [pool drain]; 15 16 return 0; 17 }
执行上面示例代码,得到以下结果 -
1 2018-11-16 04:56:39.054 main[109095] Current date is 2018-11-16 2 2018-11-16 04:56:39.054 main[109095] NewDate: 2018-11-16 00:00:00 +0000
正如在上面的程序中看到的那样,使用NSDate类对象获得当前时间。
NSDateFormatter是负责转换格式的类。
可以根据可用数据更改日期格式。例如,当想要为上面的例子添加时间点时,日期格式可以改为@"yyyy-MM-dd:hh:mm:ss"
4、异常处理
在Objective-C中提供了基础类 - NSException用于异常处理。
使用以下块实现异常处理 -
- @try- 此块尝试执行一组语句。
- @catch- 此块尝试捕获- try块中的异常。
- @finally- 此块包含始终执行的一组语句。
示例代码 -
1 #import <Foundation/Foundation.h> 2 3 int main() { 4 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 5 NSMutableArray *array = [[NSMutableArray alloc]init]; 6 7 @try { 8 NSString *string = [array objectAtIndex:10]; 9 } @catch (NSException *exception) { 10 NSLog(@"%@ ",exception.name); 11 NSLog(@"Reason: %@ ",exception.reason); 12 } 13 14 @finally { 15 NSLog(@"@@finaly Always Executes"); 16 } 17 18 [pool drain]; 19 return 0; 20 }
执行上面示例代码,得到以下结果 -
1 2018-11-16 05:01:49.924 main[43936] NSRangeException 2 2018-11-16 05:01:49.926 main[43936] Reason: Index 10 is out of range 0 (in 'objectAtIndex:') 3 2018-11-16 05:01:49.926 main[43936] @@finaly Always Executes
在上面的程序中,由于使用了异常处理,在执行过程中能够继续运行使用后续程序,而不是程序因异常而终止。
5、文件处理
使用NSFileManager类可以进行文件处理,这些示例不适用于在线编译器。
文件处理中使用的方法
下面列出了用于访问和操作文件的方法列表。 在这里,必须将FilePath1,FilePath2和FilePath字符串替换为所需的完整文件路径,以获得所需的操作。
5.1 检查文件是否存在于路径中
1 NSFileManager *fileManager = [NSFileManager defaultManager]; 2 3 //Get documents directory 4 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains 5 (NSDocumentDirectory, NSUserDomainMask, YES); 6 NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0]; 7 8 if ([fileManager fileExistsAtPath:@""] == YES) { 9 NSLog(@"File exists"); 10 }
5.2 比较两个文件内容
1 if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) { 2 NSLog(@"Same content"); 3 }
5.3 检查是否可写,可读和可执行
1 if ([fileManager isWritableFileAtPath:@"FilePath"]) { 2 NSLog(@"isWritable"); 3 } 4 5 if ([fileManager isReadableFileAtPath:@"FilePath"]) { 6 NSLog(@"isReadable"); 7 } 8 9 if ( [fileManager isExecutableFileAtPath:@"FilePath"]) { 10 NSLog(@"is Executable"); 11 }
5.4 移动文件
1 if([fileManager moveItemAtPath:@"FilePath1" 2 toPath:@"FilePath2" error:NULL]) { 3 NSLog(@"Moved successfully"); 4 }
5.5 复制文件
1 if ([fileManager copyItemAtPath:@"FilePath1" 2 toPath:@"FilePath2" error:NULL]) { 3 NSLog(@"Copied successfully"); 4 }
5.6 删除文件
1 if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) { 2 NSLog(@"Removed successfully"); 3 }
5.7 读取文件
NSData *data = [fileManager contentsAtPath:@"Path"];
5.8 写入文件
[fileManager createFileAtPath:@"" contents:data attributes:nil];
前面已成功学习了各种文件访问和操作技术,现在你应该对文件进行各种操作以及文件的使用所有了解。
6、URL加载系统
URL加载在访问URL(即来自互联网的项目)时很有用。 它是在以下类别的帮助下提供的 -
- NSMutableURLRequest
- NSURLConnection
- NSURLCache
- NSURLAuthenticationChallenge
- NSURLCredential
- NSURLProtectionSpace
- NSURLResponse
- NSURLDownload
- NSURLSession
下面是一个简单的url加载示例。它不能在命令行上运行。需要创建Cocoa应用程序。
这可以通过在XCode中选择New,然后选择Project并在出现的窗口的OS X应用程序部分下选择Cocoa Application 来完成。
单击下一步完成步骤序列,系统将要求您提供项目名称,填写项目名称为项目命名。
appdelegate.h 文件如下 -
1 #import <Cocoa/Cocoa.h> 2 3 @interface AppDelegate : NSObject <NSApplicationDelegate> 4 5 @property (assign) IBOutlet NSWindow *window; 6 7 @end
将AppDelegate.m 文件更新为以下内容 -
1 #import "AppDelegate.h" 2 3 @interface SampleClass:NSObject<NSURLConnectionDelegate> { 4 NSMutableData *_responseData; 5 } 6 7 - (void)initiateURLConnection; 8 @end 9 10 @implementation SampleClass 11 - (void)initiateURLConnection { 12 13 // Create the request. 14 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://date.jsontest.com"]]; 15 16 // Create url connection and fire request 17 NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 18 [conn start]; 19 } 20 21 #pragma mark NSURLConnection Delegate Methods 22 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 23 // A response has been received, this is where we initialize the instance var you created 24 // so that we can append data to it in the didReceiveData method 25 // Furthermore, this method is called each time there is a redirect so reinitializing it 26 // also serves to clear it 27 _responseData = [[NSMutableData alloc] init]; 28 } 29 30 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 31 // Append the new data to the instance variable you declared 32 [_responseData appendData:data]; 33 } 34 35 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection 36 willCacheResponse:(NSCachedURLResponse*)cachedResponse { 37 // Return nil to indicate not necessary to store a cached response for this connection 38 return nil; 39 } 40 41 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { 42 // The request is complete and data has been received 43 // You can parse the stuff in your instance variable now 44 NSLog(@"%@",[[NSString alloc]initWithData:_responseData encoding:NSUTF8StringEncoding]); 45 } 46 47 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 48 // The request has failed for some reason! 49 // Check the error var 50 } 51 @end 52 53 @implementation AppDelegate 54 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 55 SampleClass *sampleClass = [[SampleClass alloc]init]; 56 [sampleClass initiateURLConnection]; 57 // Insert code here to initialize your application 58 } 59 @end
现在,当编译并运行程序时,将得到以下结果。
1 2018-09-29 06:50:31.953 NSURLConnectionSample[1444:303] { 2 "time": "06:21:51 AM", 3 "milliseconds_since_epoch": 1570453631948, 4 "date": "09-29-2018" 5 }
在上面的程序中,创建了一个简单的URL连接,它以JSON格式返回并显示时间。

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号