iPhone开发技巧之网络篇(3)--- 使用NSOperation建立多任务网络连接
在网络应用程序中,经常需要多任务连接来提高程序的性能。比如多任务下载,多任务HTTP请求等,即线程控制模型中的工作群模型。使用 NSOperation 可以很容易实现这个功能。下面就以使用NSOperation处理并行的HTTP请求为例子,说明其用法。
首先准备一个 NSOperation 的子类,用于处理 HTTP 请求。
1 2 3 4 5 6 7 8 | @interface RequestOperation : NSOperation { NSURLRequest* _request; NSMutableData* _data; } - (id)initWithRequest:(NSURLRequest *)request; @end |
[UIImage imageNamed:ImageName];
NSString *thumbnailFile = [NSString stringWithFormat:@"%@/%@.png", [[NSBundle mainBundle] resourcePath], fileName]; UIImage *thumbnail = [UIImage imageWithContentsOfFile:thumbnailFile];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath]
- (void)readPlist
{
//取得檔案路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/data.plist"];
//
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *plistDict;
if ([fileManager fileExistsAtPath: filePath]) //檢查檔案是否存在
{
plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
}else{
plistDict = [[NSMutableDictionary alloc] init];
}
NSString *value;
value = [plistDict objectForKey:@"version"];
[plistDict release];
}
//存檔
- (void)writePlist
{
//取得檔案路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/data.plist"];
//
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *plistDict;
if ([fileManager fileExistsAtPath: filePath]) //檢查檔案是否存在
{
plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
}else{
plistDict = [[NSMutableDictionary alloc] init];
}
[plistDict setValue:@"1.0.0" forKey:@"version"];
//存檔
if ([plistDict writeToFile:filePath atomically: YES]) {
NSLog(@"writePlist success");
} else {
NSLog(@"writePlist fail");
}
[plistDict release];
}
1
2
3
4
5
6
7
8
|
NSString *str1 = @"Homebrew";
NSString *str2 = @"Homebrew";
// This compares the addresses of the string
if (str1 == str2)
NSLog (@"str1 equals str2");
else
NSLog (@"str1 does not equal str2");
|
1
2
3
4
5
6
7
8
9
10
|
// Create a C string
char *cStr = "Homebrew";
NSString *str3 = [NSString stringWithUTF8String:cStr];
NSString *str4 = @"Homebrew";
// Wrong - this compares the address of the string
if (str3 == str4)
NSLog (@"str3 equals str4");
else
NSLog (@"str3 does not equal str4");
|
1
2
3
4
5
6
7
8
|
char *cStr = "Homebrew";
NSString *str3 = [NSString stringWithUTF8String:cStr];
NSString *str4 = @"Homebrew";
if ([str3 isEqualToString:str4])
NSLog (@"str3 equals str4");
else
NSLog (@"str3 does not equal str4");
|