89283517 2013-05-30
objective-c最后一节笔记
// NSDate *date=[NSDate date];//这里的时间是GMT时间是。格林尼标准时间和北京时间相差8个小时,因为北京在东八区。
// NSDate *date1=[NSDate dateWithTimeInterval:60*60*8 sinceDate:date];//加8个小时
// 字典加数组操作
// NSArray *keys = [@"one two three" componentsSeparatedByString:@" "];
// NSArray *value = [@"two bravo a" componentsSeparatedByString:@" "];
// NSDictionary *dic = [[NSDictionary alloc]initWithObjects:value forKeys:keys];
// NSLog(@"%s",[[dic description] UTF8String]);//返回类型是NSString;
// NSLog(@"%@",[dic objectForKey:@"one"]);
// NSLog(@"%@",keys);
// [dic release];
// NSURL *url=[[NSURL alloc]initWithString:@"http://www.baidu.com"];
// NSString *astring = [[NSString alloc] initWithContentsOfURL:url];
// NSLog(@"astring:%@",astring);
// NSMutableArray *arry=[[NSMutableArray alloc ]initWithObjects:@"987",@"654",@"321",@"000", nil];
//
// for (NSString *element in arry ) {
// NSLog(@"element:%@",element);
// }
//创建文件管理器;
// NSFileManager *filem=[NSFileManager defaultManager];
// //指定要存档的路径
// NSString *path=[NSString stringWithFormat: @"/Users/ibokan/Desktop/a6.txt"];
// // NSString *path1=[NSString stringWithFormat:@"/Users/ibokan/Desktop/a1.txt"];
// //添加字符串信息;
// NSMutableString *str=[NSMutableString stringWithFormat:@"abc"];
// //2个属性间用-分割。
// [str appendFormat:@"\n"];
// [str appendFormat:@"%d",55];
// [str appendFormat:@"-"];
// [str appendFormat:@"%d",333];
// //将字符串对象转换为NSData类型的对象。
// NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
//
// if ([filem fileExistsAtPath:path]) {
// NSLog(@"文件已经存在,不能再创建。");
// }
// else{
// [filem createFileAtPath:path contents:data attributes:nil];
// //[filem
// }
// NSString *s=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
// NSArray *array=[s componentsSeparatedByString:@"\n"];
// NSString *a1=[array objectAtIndex:0];
// NSString *a2=[array objectAtIndex:1];
// NSLog(@"a1==%@,a2==%@",a1,a2);
//
// //[filem removeItemAtPath:@"/Users/ibokan/Desktop/a6.txt" error:nil];
// //获取指定路径的文件数据
// NSString *file=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
// //添加指定的信息
// NSString *addFile=[file stringByAppendingFormat:@"hello"];
// //把添加的信息写入文件。
// [addFile writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:nil];
// NSLog(@"addFile==%@",addFile);
// //用NSData类型接受网络数据,可以提快速度。
// NSData *dt=[NSData dataWithContentsOfFile:path];
// //转换为NSString类型。
// NSString *dtString =[NSString stringWithCString:[dt bytes] encoding:NSUTF8StringEncoding];
// NSString *addt=[dtString stringByAppendingFormat:@"piaoliang"];
// [addt writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:nil];
// //新建一个url
// NSURL *url=[NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
// //新建一个请求
// NSURLRequest *request=[NSURLRequest requestWithURL:url];
// //新建连接
// [NSURLConnection connectionWithRequest:request delegate:self];
//
// NSLog(@"NSURLConnection完成");
注意到writeToFile:方法中的单词atomically了吗?这种调用有什么负面作用吗?没有。atomically:参数的值为BOOL类型,用于通知Cocoa是否应该首先将文件内容保存在临时文件中,当文件成功保存后,在将该临时文件和原始文件交换。这是一种安全机制:如果在保存过程中出现意外,不会破坏原始文件,但这种安全机制需要付出一定的代价:在保存过程中,由于原始文件仍然保存在磁盘中,所以需要使用双倍的磁盘空间。除非保存的文件非常大,将会占用用户硬盘的空间,否则应该自动保存文件。
#import "ViewController.h"
#import "GDataXMLNode.h"
#import "JSON.h"
@implementation ViewController
@synthesize finaldata=_finaldata;
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"连接开始");
//初始化_finaldata
_finaldata=[[NSMutableDataalloc]initWithCapacity:1024];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"接受数据");
//每次回调函数将接受到的data附加到finaldata
[self.finaldata appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
//创建图片view
UIImageView *view=[[UIImageViewalloc]initWithFrame:CGRectMake(0, 100, 320, 320)];
//创建图片
UIImage *image=[UIImage imageWithData:self.finaldata];
//图片放入view
view.image=image;
[self.view addSubview:view];
//测试下载图片到本地
//下载的目录
NSString *path=[[NSBundlemainBundle]bundlePath];
NSString *urlname=@"http://best50.cn:8080/update/10/food/72.jpg";
// NSLog(@"%@",[urlname lastPathComponent]);
// NSLog(@"%@",path);
//具体路径
NSString *filepath=[path stringByAppendingPathComponent:[urlname lastPathComponent]];
NSFileManager *fm=[NSFileManagerdefaultManager];
if([fm createFileAtPath:filepath contents:self.finaldataattributes:nil]){
NSLog(@"下载成功");
}
}
-(void) loadImage:(id) sender{
//测试异步连接
//1创建url对象
//http://best50.cn:8080/update/10/food/72.jpg
//2创建请求对象
NSURLRequest *request=[NSURLRequestrequestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheDatatimeoutInterval:10];
//3发起异步请求,并设置代理
[NSURLConnectionconnectionWithRequest:request delegate:self];
}
-(void)showImage:(id)sender{
//测试异步连接
//创建url对象
//这个路径不知道为什么不能用。
//创建请求对象。
NSURLRequest *request1=[NSURLRequestrequestWithURL:url1 cachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:122];
//发起异步请求。并设置代理。
[NSURLConnectionconnectionWithRequest:request1 delegate:self];
}
- (void)viewDidLoad
{
[superviewDidLoad];
// UIButton *btn=[UIButton buttonWithType:1];
// btn.frame=CGRectMake(0, 0, 100, 80);
// [btn setTitle:@"piaoliang" forState:UIControlStateNormal];
// [btn addTarget:self action:@selector(showImage:) forControlEvents:UIControlEventTouchUpInside];
// [self.view addSubview:btn];
//1测试get同步连接
//1创建url对象
//http://api.hudong.com/iphonexml.do?type=focus-c
// NSURL *url=[NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
// //2创建请求对象
// NSURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
// //3创建响应和错误指针对象
// NSHTTPURLResponse *response=nil;
// NSError *error=nil;
// //4创建连接对象发起同步连接,并将返回数据存入data
// NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// //5打印请求status,和错误status
// NSLog(@"response=%@",[NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]);
// NSLog(@"error=%@",[error localizedDescription]);
// //6将内容打印输出
// NSLog(@"data=%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
//2测试post同步连接
//1创建url对象
//http://api.hudong.com/iphonexml.do?type=focus-c
// NSURL *url=[NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
// //2创建请求对象
// NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
// //2.5设置请求为post
// [request setHTTPMethod:@"post"];
// //3创建响应和错误指针对象
// NSHTTPURLResponse *response=nil;
// NSError *error=nil;
// //4创建连接对象发起同步连接,并将返回数据存入data
// NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// //5打印请求status,和错误status
// NSLog(@"response=%@",[NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]);
// NSLog(@"error=%@",[error localizedDescription]);
// //6将内容打印输出
// NSLog(@"data=%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
//3测试异步连接请求图片并下载到本地
UIButton *btn=[UIButtonbuttonWithType:1];
btn.frame=CGRectMake(0, 0, 100, 80);
[btn setTitle:@"点一点"forState:UIControlStateNormal];
[btn addTarget:selfaction:@selector(loadImage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
//4测试xml本地文件解析
// NSString *path=[[NSBundle mainBundle]bundlePath];
// NSString *filepath=[path stringByAppendingPathComponent:@"Student.xml"];
// NSString *str1=[NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
// NSLog(@"%@",str1);
// //解析文档
// //1创建要解析的XML文档对象
// GDataXMLDocument *doc=[[GDataXMLDocument alloc]initWithXMLString:str1 options:0 error:nil];
// //2获取要解析文档的root元素
// GDataXMLElement *root=doc.rootElement;
// //3从根元素获取元素
// NSArray *docList=[root elementsForName:@"student"];
// NSLog(@"docList==%@",docList);
// //4获取第一个student元素
// GDataXMLElement *de1=[docList objectAtIndex:0];
// NSLog(@"de1==%@",de1);
// //5获取子元素
// NSArray *stuAry1=[de1 children];
// NSLog(@"stuAry1==%@",stuAry1);
// //获取每个子元素
// for (GDataXMLElement *e in stuAry1) {
// NSLog(@"%@=%@",e.name,e.stringValue);
// }
//5json解析测试,测试读取本地JSON文件内容
// NSString *jpath=[path stringByAppendingPathComponent:@"student.json"];
// NSString * strJson = [NSString stringWithContentsOfFile:jpath encoding:NSUTF8StringEncoding error:nil];
// NSArray * arr= [strJson JSONValue];
// for (int i=0; i<2; i++) {
// NSDictionary * dic = [arr objectAtIndex:i];
// for(id s in dic)
// {
// NSLog(@"%@=%@",s,[dic objectForKey:s]);
// }
// }
}
- (void)viewDidUnload
{
[superviewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[superviewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[superviewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end