Gowhich

Durban's Blog

同步下载(交互不好,容易出现卡死现象,一般下载数据较小或有特定需求才使用)。 发送同步请求后,程序将停止用户交互,直到服务器返回数据完成后,才进行下一步的操作。

步骤:

创建NSURL

1
NSURL *url = [[NSURL alloc] initWithString:@"http://www.baidu.com/"];

通过URL创建NSURLRequest

1
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];

cachePolicy 缓存协议是个枚举类型:

NSURLRequestUseProtocolCachePolicy 基础策略

NSURLRequestReloadIgnoringLocalCacheData 忽略本地缓存

NSURLRequestReturnCacheDataElseLoad 首先使用缓存,如果没有本地缓存,才从原地址下载

NSURLRequestReturnCacheDataDontLoad 使用本地缓存,从不下载,如果本地没有缓存,则请求失败。此策略多用于离线操作

NSURLRequestReloadIgnoringLocalAndRemoteCacheData 无视任何的缓存策略,无论是本地还是远程,总是从原地址重新下载

NSURLRequestReloadRevalidatingCacheData 如果本地缓存是有效的则不下载。其他任何情况都从原地址重新下载

建立网络连接NSURLConnection,同步请求数据

1
NSData *receivedData = (NSMutableData *)[NSURLConnection sendSynchronousRwquest:request returningResponse:&response error:&error];

以上三步后,就需要将receivedData进行解析,一般是XML/JSON

实例演示:

detailViewController.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import <UIKit/UIKit.h>

@interface vlinkagePersonViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

//生成content的key值
@property (strong, nonatomic) NSArray *keys;
//生成content的value值
@property (strong, nonatomic) NSArray *objects;
//列表内容
@property (strong, nonatomic) NSDictionary *content;

//艺人的数据
@property (retain, nonatomic) NSMutableData *personData;

//艺人的数组数据
@property (retain, nonatomic) NSArray *person;
@end
detailViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#import "vlinkagePersonViewController.h"

@interface vlinkagePersonViewController ()

@end

@implementation vlinkagePersonViewController

@synthesize content;
@synthesize personData;
@synthesize person;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.


NSURL *url = [[NSURL alloc] initWithString:@"http://xxx.xxx.xxx.xxx:xxx/person/actorlist?order_by=index&start_date=2012-06-01&end_date=2012-07-01&start=1&offset=10&app_key=KSKdzSyeb99YdLwTMrzvuLumNYCM6pzT4Z3f27R4L3qq6jCs"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];

NSURLResponse *response = [[NSURLResponse alloc] init];
NSError *error = [[NSError alloc] init];

NSMutableData *receivedData = (NSMutableData *)[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


self.person = [self readJsonData:receivedData];

if([self.person isKindOfClass:[NSDictionary class]]){
NSLog(@"NSDictionary");
}

if([self.person isKindOfClass:[NSArray class]]){
NSLog(@"NSArray");
}

}

-(NSArray *) readJsonData:(NSMutableData *)data{
//NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)
//和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)。
NSError *error;
NSDictionary *personDictionary = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSDictionary *personInfo = [personDictionary objectForKey:@"data"];

NSArray *personList = [personInfo objectForKey:@"list"];

return personList;
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}


-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
return [self.person count];
}


-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

static NSString *CellIdentifier = @"Cell";
UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];

}

NSDictionary *dic=[self.person objectAtIndex:indexPath.row];
NSString *name=[dic objectForKey:@"zh_name"];

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = name;

return cell;

}
@end

结果还会将数据显示到table中

异步下载支持应用程序在后台下载数据,在等待下载完成的过程中不会阻塞代码的运行

代码如下:

detailViewController.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#import <UIKit/UIKit.h>

@interface vlinkagePersonViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

//生成content的key值
@property (strong, nonatomic) NSArray *keys;
//生成content的value值
@property (strong, nonatomic) NSArray *objects;
//列表内容
@property (strong, nonatomic) NSDictionary *content;

//艺人的数据
@property (retain, nonatomic) NSMutableData *personData;

@end
detailViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#import "vlinkagePersonViewController.h"

@interface vlinkagePersonViewController ()

@end

@implementation vlinkagePersonViewController

@synthesize content;
@synthesize personData;


- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.


NSURL *url = [[NSURL alloc] initWithString:@"http://xxx.xxx.xxx.xxx:xxx/person/actorlist?order_by=index&start_date=2012-06-01&end_date=2012-07-01&start=1&offset=10&app_key=KSKdzSyeb99YdLwTMrzvuLumNYCM6pzT4Z3f27R4L3qq6jCs"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if(!connection){
NSLog(@"链接失败!");
}else{
self.personData = [NSMutableData data];
self.content = [[NSDictionary alloc] init];
}
NSLog(@"content = %@",self.content);
}

//回掉方法
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse");
[self.personData setLength:0];
}

//将接收到的数据存储到字符串中
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"didReceiveData");
[self.personData appendData:data];
}

//下载已经完成
- (void)connectionDidFinishLoading: (NSURLConnection *) connection{
NSLog(@"connectionDidFinishLoading");
//调用函数解析下载到的json格式的数据
[self readJsonData];
NSLog(@"content %@",self.content);
}

//下载失败
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
message:[error localizedFailureReason]
delegate:self
cancelButtonTitle:@"OK!"
otherButtonTitles:nil];
[errorAlert show];

}

-(void) readJsonData{
//NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)
//和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)。
NSError *error;
NSDictionary *personDictionary = [NSJSONSerialization JSONObjectWithData:self.personData
options:NSJSONReadingMutableContainers
error:&error];
NSDictionary *personInfo = [personDictionary objectForKey:@"data"];
NSDictionary *personList = [personInfo objectForKey:@"list"];
self.content = personList;
NSLog(@"personList %@",personList);
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}


-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
return 1;
}


-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

static NSString *CellIdentifier = @"Cell";
UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text=@"话题";

return cell;

}
@end

输出的结果是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
2013-04-26 16:45:55.174 vlinkagePerson3[67809:c07] content = {
}
2013-04-26 16:45:55.501 vlinkagePerson3[67809:c07] didReceiveResponse
2013-04-26 16:45:55.501 vlinkagePerson3[67809:c07] didReceiveData
2013-04-26 16:45:55.502 vlinkagePerson3[67809:c07] connectionDidFinishLoading
2013-04-26 16:45:55.502 vlinkagePerson3[67809:c07] personList (
{
id = 175;
"is_attention" = 0;
score = "7.84948333";
"zh_name" = "\U5b59\U4fea";
},
{
id = 1582;
"is_attention" = 0;
score = "7.78961667";
"zh_name" = "\U949f\U6c49\U826f";
},
{
id = 17577;
"is_attention" = 0;
score = "7.69375000";
"zh_name" = "\U5f20\U6839\U7855";
},
{
id = 35;
"is_attention" = 0;
score = "7.60104167";
"zh_name" = "\U6768\U5e42";
},
{
id = 3880;
"is_attention" = 0;
score = "7.56774167";
"zh_name" = "\U6797\U4f9d\U6668";
},
{
id = 94;
"is_attention" = 0;
score = "7.56668333";
"zh_name" = "\U674e\U5c0f\U7490";
},
{
id = 504;
"is_attention" = 0;
score = "7.48178333";
"zh_name" = "\U5f20\U6aac";
},
{
id = 3571;
"is_attention" = 0;
score = "7.46722500";
"zh_name" = "\U9a6c\U5929\U5b87";
},
{
id = 228;
"is_attention" = 0;
score = "7.45210000";
"zh_name" = "\U5b8b\U4e39\U4e39";
},
{
id = 329;
"is_attention" = 0;
score = "7.44270833";
"zh_name" = "\U80e1\U6b4c";
}
)
2013-04-26 16:45:55.503 vlinkagePerson3[67809:c07] content (
{
id = 175;
"is_attention" = 0;
score = "7.84948333";
"zh_name" = "\U5b59\U4fea";
},
{
id = 1582;
"is_attention" = 0;
score = "7.78961667";
"zh_name" = "\U949f\U6c49\U826f";
},
{
id = 17577;
"is_attention" = 0;
score = "7.69375000";
"zh_name" = "\U5f20\U6839\U7855";
},
{
id = 35;
"is_attention" = 0;
score = "7.60104167";
"zh_name" = "\U6768\U5e42";
},
{
id = 3880;
"is_attention" = 0;
score = "7.56774167";
"zh_name" = "\U6797\U4f9d\U6668";
},
{
id = 94;
"is_attention" = 0;
score = "7.56668333";
"zh_name" = "\U674e\U5c0f\U7490";
},
{
id = 504;
"is_attention" = 0;
score = "7.48178333";
"zh_name" = "\U5f20\U6aac";
},
{
id = 3571;
"is_attention" = 0;
score = "7.46722500";
"zh_name" = "\U9a6c\U5929\U5b87";
},
{
id = 228;
"is_attention" = 0;
score = "7.45210000";
"zh_name" = "\U5b8b\U4e39\U4e39";
},
{
id = 329;
"is_attention" = 0;
score = "7.44270833";
"zh_name" = "\U80e1\U6b4c";
}
)

  • KissXml——xml解析库
    相关教程:http://www.iteye.com/topic/625849
    http://sencho.blog.163.com/blog/static/83056228201151743110540/
    很方便的一个xml解析器,支持Xpath查询。

  • skpsmtpmessage——Quick SMTP邮件发送
    svn checkout http://skpsmtpmessage.googlecode.com/svn/trunk/ skpsmtpmessage-read-only
    github: git clone https://github.com/kailoa/iphone-smtp.git
    相关教程:http://disanji.net/2011/01/28/skpsmtpmessage-open-source-framework/
    skpsmtpmessage 是由Skorpiostech, Inc.为我们带来的一个SMTP协议的开源实现,使用Objective-c 实现,iOS系统的项目可以直接调用。

  • jsonframework——JSON支持
    相关教程:http://blog.csdn.net/xiaoguan2008/article/details/6732683
    它是一个开源框架,基于BSD协议发布。由于json-framework是开放源代码的,当你需要使用它时你只需将json的源代码加入到你的工程中。

  • ASIHttpRequest——HTTP Network库
    ASIHttpRequest库极大的简化了网络通 信,提供更先进的工具,例如文件上传工具,重定向处理工具、验证工具、等等。

  • MBProgressHUD——进展指示符库
    苹果的应用程序一般都会用一种优雅的,半透明的进度显示效果,不过这个API是不公开的,因此你要是用了,很可能被清除出AppStore。而 MBProgressHUD提供了一个替代方案,而且在用户角度上,实现的效果根本看不出和官方程序有什么差别。同时还提供了其他附加功能,比如虚拟进展 指示符,以及完成提示信息。整合到项目里也很容易,这里不细谈了。

  • zxing——二维码扫描库
    支持条形码/二维码扫描的图形处理库,这是一个java库,在android上的功能比较完整。同时该库也支持ios,但只能支持二位条形码的扫描。

  • kal——iPhone日历控件
    一个类似于ios系统默认日历开源日历库,支持添加事件,自定义日历样式等功能。

  • Facebook iOS SDK——Facebook API类库
    大体来讲就是iPhone上的Facebook login,完全支持Facebook Graph API和the older REST api。

  • shareKit——分享库
    相关demo:http://www.cocoachina.com/bbs/read.php?tid-71760.html
    分享到开心,豆瓣,腾讯,新浪微博的api所用到的强大的分享库。

  • SDWebImage——简化网络图片处理
    用SDWebImage调用网站上的图片,跟本地调用内置在应用包里的图片一样简单。操作也很简单。

  • GData client——iPhone上所有Google相关服务的类库
    名字就说明一切了。跟Google相关的,值得一提的是,这个项目很开放。有很多示例程序供下载。

  • CorePlot——2D图形绘图仪
    CorePlot有很多解决方案将你的数据可视。同时也会提供各种迷人的图形效果,比如棒状图、饼状图、线状图等等,在他们网站上也提供了大量的范例图形,很多股票价格应用,游戏分数,个人财务管理都在用。

  • Three20——类似于Facebook的优秀的UI库
    Three20类库是Facebook自己做的,大而全是他最大的特色。把他整合到已有的项目中可能得费点周折,不过如果一开始你就用上了Three20,尤其是牵扯到很多web相关的项目的时候,你就能深刻体会到神马叫给力了。

  • FMDatabase——SQLite的Objective-C封装
    是SQLite的C API對初學者來說實在太麻煩太瑣碎,難度太高。FMDB說穿了其實只是把C API包裝成簡單易用的Objective-C类。對于SQLite初學者來說,大大減低了上手的難度。有了FMDB,寫程式時只要專心在SQLite的語法上,而不用去理那堆有看沒有懂的C API,實在是件快樂的事情。

来源:http://blog.csdn.net/jiarusun000/article/details/7170577

Core-Plot的安装见我的另外一篇文章 iOS 使用 Core Plot 绘制统计图表入门,

创建图表以及将图表放到视图上的方法是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(@"title = %@",self.title);


//创建图表
graph = [[CPTXYGraph alloc] initWithFrame:self.view.bounds];

//给图表添加一个主题
CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
[graph applyTheme:theme];

//创建画板,将图表添加到画板
CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds];
hostingView.hostedGraph = graph;
[self.view addSubview:hostingView];


//设置图表的边框
//左边的padding设置为0
graph.paddingLeft = 0;
//顶部的的padding设置0
graph.paddingTop = 0;
//右边的padding设置为0
graph.paddingRight = 0;
//底部的padding设置为0
graph.paddingBottom = 0;

//坐标区域的边框设置
//左边的padding设置为45.0
graph.plotAreaFrame.paddingLeft = 40.0 ;
//顶部的padding设置为40.0
graph.plotAreaFrame.paddingTop = 40.0 ;
//右边的padding设置为5.0
graph.plotAreaFrame.paddingRight = 15.0 ;
//底部的padding设置为80.0
graph.plotAreaFrame.paddingBottom = 80.0 ;


//设置坐标范围
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(200.0)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(200.0)];

//设置坐标刻度大小
CPTXYAxisSet *axisSet = (CPTXYAxisSet *) graph.axisSet ;
CPTXYAxis *x = axisSet.xAxis ;
//x 轴:不显示小刻度线
x. minorTickLineStyle = nil ;
// 大刻度线间距: 50 单位
x. majorIntervalLength = CPTDecimalFromString (@"50");
// 坐标原点: 0
x. orthogonalCoordinateDecimal = CPTDecimalFromString ( @"0" );

CPTXYAxis *y = axisSet.yAxis ;
//y 轴:不显示小刻度线
y. minorTickLineStyle = nil ;
// 大刻度线间距: 50 单位
y. majorIntervalLength = CPTDecimalFromString ( @"50" );
// 坐标原点: 0
y. orthogonalCoordinateDecimal = CPTDecimalFromString (@"0");

//创建绿色区域
dataSourceLinePlot = [[CPTScatterPlot alloc] init];
dataSourceLinePlot.identifier = @"Green Plot";

//设置绿色区域边框的样式
CPTMutableLineStyle *lineStyle = [dataSourceLinePlot.dataLineStyle mutableCopy];
//设置线的宽度
lineStyle.lineWidth = 1.f;
//设置线的颜色
lineStyle.lineColor = [CPTColor greenColor];
//添加线到绿色区域中
dataSourceLinePlot.dataLineStyle = lineStyle;
//设置透明实现添加动画
dataSourceLinePlot.opacity = 0.0f;

//设置数据元代理
dataSourceLinePlot.dataSource = self;
//绿色区域添加到图表中
[graph addPlot:dataSourceLinePlot];

// 创建一个颜色渐变:从 建变色 1 渐变到 无色
CPTGradient *areaGradient = [ CPTGradient gradientWithBeginningColor :[CPTColor greenColor] endingColor :[CPTColor colorWithComponentRed:0.65 green:0.65 blue:0.16 alpha:0.2]];
// 渐变角度: -90 度(顺时针旋转)
areaGradient.angle = -90.0f ;
// 创建一个颜色填充:以颜色渐变进行填充
CPTFill *areaGradientFill = [ CPTFill fillWithGradient :areaGradient];
// 为图形设置渐变区
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPTDecimalFromString ( @"0.0" );
dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationLinear ;


dataForPlot1 = [[NSMutableArray alloc] init];
[self plotData];
}

里面调用了一个方法:plotData

有了上面的操作,其他的就是添加数据和显示数据了

下面给出方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//添加数据
-(void) plotData{
if ([dataSourceLinePlot.identifier isEqual:@"Green Plot"]) {
NSString *xp1 = [NSString stringWithFormat:@"%d",1];
NSString *yp1 = [NSString stringWithFormat:@"%d",10];
NSMutableDictionary *point1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp1, @"x", yp1, @"y", nil];
[dataForPlot1 insertObject:point1 atIndex:0];

NSString *xp2 = [NSString stringWithFormat:@"%d",10];
NSString *yp2 = [NSString stringWithFormat:@"%d",25];
NSMutableDictionary *point2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp2, @"x", yp2, @"y", nil];
[dataForPlot1 insertObject:point2 atIndex:1];

NSString *xp3 = [NSString stringWithFormat:@"%d",30];
NSString *yp3 = [NSString stringWithFormat:@"%d",15];
NSMutableDictionary *point3 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp3, @"x", yp3, @"y", nil];
[dataForPlot1 insertObject:point3 atIndex:2];

NSString *xp4 = [NSString stringWithFormat:@"%d",50];
NSString *yp4 = [NSString stringWithFormat:@"%d",80];
NSMutableDictionary *point4 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp4, @"x", yp4, @"y", nil];
[dataForPlot1 insertObject:point4 atIndex:3];

NSString *xp5 = [NSString stringWithFormat:@"%d",70];
NSString *yp5 = [NSString stringWithFormat:@"%d",60];
NSMutableDictionary *point5 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp5, @"x", yp5, @"y", nil];
[dataForPlot1 insertObject:point5 atIndex:4];

NSString *xp6 = [NSString stringWithFormat:@"%d",90];
NSString *yp6 = [NSString stringWithFormat:@"%d",100];
NSMutableDictionary *point6 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp6, @"x", yp6, @"y", nil];
[dataForPlot1 insertObject:point6 atIndex:5];

NSString *xp7 = [NSString stringWithFormat:@"%d",110];
NSString *yp7 = [NSString stringWithFormat:@"%d",70];
NSMutableDictionary *point7 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp7, @"x", yp7, @"y", nil];
[dataForPlot1 insertObject:point7 atIndex:6];

NSString *xp8 = [NSString stringWithFormat:@"%d",130];
NSString *yp8 = [NSString stringWithFormat:@"%d",80];
NSMutableDictionary *point8 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp8, @"x", yp8, @"y", nil];
[dataForPlot1 insertObject:point8 atIndex:7];

NSString *xp9 = [NSString stringWithFormat:@"%d",200];
NSString *yp9 = [NSString stringWithFormat:@"%d",135];
NSMutableDictionary *point9 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:xp9, @"x", yp9, @"y", nil];
[dataForPlot1 insertObject:point9 atIndex:8];
}
}

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot{
return [dataForPlot1 count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSString *key = (fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y");
NSNumber *num;
//让视图偏移
if ( [(NSString *)plot.identifier isEqualToString:@"Green Plot"] ) {
num = [[dataForPlot1 objectAtIndex:index] valueForKey:key];
if ( fieldEnum == CPTScatterPlotFieldX ) {
num = [NSNumber numberWithDouble:[num doubleValue] - r];
}
}
//添加动画效果
CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeInAnimation.duration = 1.0f;
fadeInAnimation.removedOnCompletion = NO;
fadeInAnimation.fillMode = kCAFillModeForwards;
fadeInAnimation.toValue = [NSNumber numberWithFloat:2.0];
[dataSourceLinePlot addAnimation:fadeInAnimation forKey:@"animateOpacity"];
return num;
}

头文件的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"

@interface DetailsViewController : UIViewController<CPTPlotDataSource, CPTAxisDelegate>
{
CPTXYGraph *graph; //画板
CPTScatterPlot *dataSourceLinePlot;//线
NSMutableArray *dataForPlot1; //坐标数组
NSTimer *timer1; //定时器
int j;
int r;

}
@property (retain, nonatomic) NSMutableArray *dataForPlot1;
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSMutableArray *dataArray;

@end

1.在线查看帮助文件:

Xcode下查看帮助文件,菜单Help-Developer Documentation在右上角搜索框中即可检索,但速度很慢,在线查看。

2.下载帮助文件到本地:

要想下载帮助文件,菜单Xcode-preferences-Documentation 右键Get Info可以看到Feed URL找到.atom文件地址,用FF浏览器访问可以看到下载列表,用迅雷下载即可。

atom链接如下,复制到浏览器地址栏即可见到下载列表(用IE浏览器好像不行)

http://developer.apple.com/rss/com.apple.adc.documentation.AppleiPhone4\_2.atom

http://developer.apple.com/rss/com.apple.adc.documentation.AppleSnowLeopard.atom

http://developer.apple.com/rss/com.apple.adc.documentation.AppleXcode3\_2.atom

也可直接用下面的链接下载

http://devimages.apple.com/docsets/20101122/com.apple.adc.documentation.AppleLegacy.CoreReference.xar

http://devimages.apple.com/docsets/20101122/com.apple.ADC\_Reference\_Library.DeveloperTools.xar

http://devimages.apple.com/docsets/20101122/com.apple.adc.documentation.AppleSnowLeopard.JavaReference.xar

http://devimages.apple.com/docsets/20101122/com.apple.adc.documentation.AppleSnowLeopard.CoreReference.Xcode4.xar

http://devimages.apple.com/docsets/20101122/com.apple.adc.documentation.AppleiOS4\_2.iOSLibrary.Xcode4.xar

3.下载后,拷贝到Mac的/Developer/Documentations/Docset目录下,

使用终端命令:

1
sudo xar -xf 下载的文件名.xar

将其解压,然后修复权限:

1
sudo chown -R -P devdocs 解压后的文件名.docset

打开Xcode就可以离线浏览了。

$this->redirect这里的$this是当前的controller

可能是应用程序的也可能是模块下的
这里仅解一下第一个参url,当url是一个字符串时,它会自己动跳转,如$this->redirect('/'); 会跳转到站点根,如果你的当前主机为localhost,那么他就会跳到http://localhost/ 再者$this->redirect('/books');,则会跳到http://localhost/books 在应用程序的controller中,也可以使用$this->redirect('books');也会跳到http://localhost/books 但是当你在module中这样使用,则会出现另一种情况,当你打开urlManager,并设置了隐藏脚本文件,如果你当前的访问地址为 http://localhost/admin/default/index 当使用$this->redirect('books'); 跳转, 跳转后地址则是 http://localhost/admin/default/books 这里只是说一下,redirect的简单跳转,我个人建议,如果不是跳到其他项目,或外站$this->redirect('http://yiibook.com');,建议都使用下面的方法 url使用数组
当url为数组时,会调用urlManager来根据路由组织跳转的路径,这种情况比较理想,而且会根据路由的修改而改变
如果有一条路由为

1
'book'=>'admin/default/index'

格式为:’路由’=>’真实地址’,
即指定了访问book,就相当于方问admin模型下的default控制器的index操作方法。
既然使用了路由,主要是为了让url更友好,并隐藏真实地址
那么,当想使用$this->redirect跳转到这个路由时,需要指定真实地址,如

1
$this->redirect(array('admin/default/index'));

这样就会跳到这个地址了,而且url显示的确是book,而当你修路由名称时,如
‘books’=>’admin/default/index’,或干脆去掉这个路径,都不用修改你的程序
在模块中的情况,如果你当前在admin模块的controller中,使用跳转,则可以不用写moduleId
直接使用$this->redirect(array(‘default/index’)); 也是ok的,这样你的module也不会
依赖于moduleId了
再有如果你当前也在admin模块下的default控制器中,也可以使用
$this->redirect(array(‘index’));进行跳转,不依赖于控制器的名字
我们再看一下带参数的路由

1
'book<id:\d+>'=>'admin/default/index'

那么,url需要为这个路径传递一个参数id,如

1
$this->redirect(array('admin/default/index', 'id'=>1));

url格式为array(‘真实路径’, ‘参数名’=>’参数值’,’参数名2’=>’参数值2’, ….);
Yii中许多组件或方法都有支持这种url的格式,如CMenu等等。

createUrl,有$this->createUrl和Yii::app()->createUrl

createUrl它会根据真实地址,组织成路由格式的地址
根据上面的路由,创建url

1
$this->createUrl('admin/default/index')

带参数情况

1
$this->createUrl('admin/default/index', array('id'=>1));

admin模块中,使用

1
$this->createUrl('default/index');

1
$this->create('index');

不要使用Yii::app()->createUrl,避免依赖于具体的路由

注意一下redirect与createUrl的参数区别。

时区设置方法:

  • 在php.ini 文件中添加
1
date.timezone = "Asia/Chongqing"
  • 或者 php中处理代码时候 需要 echo gmdate('Y-m-d H:m:s', time()+8\*3600);

  • 在php脚本中加入代码 date\_default\_timezone\_set("Asia/Shanghai");

  • 最简便的方法,在config/main.php

1
2
3
return [
'timeZone' => 'Asia/Chongqing',
];

1,创建
按command +N快捷键创建,或者File —> New —> New File,选择Mac OS X下的Property List
创建plist文件名为plistdemo。

打开plistdemo文件,在空白出右键,右键选择Add row 添加数据,添加成功一条数据后,在这条数据上右键看到 value Type选择Dictionary。点加号添加数据。

创建完成之后用source code查看到plist文件是一个xml格式的文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>one</key>
<array>
<string>chenglong</string>
<string>lilianjie</string>
<string>zhenzidan</string>
<string>shixiaolong</string>
</array>
<key>two</key>
<array>
<string>liushishi</string>
<string>tangyan</string>
<string>zhangziyi</string>
<string>yangmi</string>
</array>
</dict>
</plist>

读取数据的方式,和方法可以参考下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)viewDidLoad
{
[super viewDidLoad];

//取得person.plist绝对路径
//person.plist本身是一个NSDictionary,以键-值的形式存储字符串数组
NSString *path=[[NSBundle mainBundle] pathForResource:@"person" ofType:@"plist"];

//转换成NSDictionary对象
NSDictionary *dict=[[NSDictionary alloc] initWithContentsOfFile:path];

self.names=dict;

//重置
[self resetSearch];

//重新载入数据
[self.table reloadData];

}

我是直接放在了viewDidLoad这个方法中

iOS(iPhone/iPad) 下图形组件有两个有名的,s7graphviewCore Plot ,它们都是在Google上托管的代码,听说 Core Plot 比较强,因为前者仅支持曲线图,后者呢曲线图、饼图、柱状图等通吃,且较活跃。那就专注下 Core Plot 的使用。它提供了 MacOSX 和 iOS 下的组件库,我只用到它的 iOS 图表库。

Core Plot能画出来图表的效果应该多看看:http://code.google.com/p/core-plot/wiki/PlotExamples,相信看过之后绝大多数的 iOS下的图表可以用它来满足你了。

配置其实很简单的,先从 http://code.google.com/p/core-plot/downloads/list下载最新版的CorePlot,比如当前是:CorePlot_0.4.zip,解压开,然后就两步:

  • 把目录 CorePlot_0.4/Binaries/

iOS中的libCorePlotCocoaTouch.a和整个子目录CorePlotHeaders从Finder中一并拖入到当前项目中,选择Copyitem into destination group’s folder (if needed),Add to targets里选上相应的target。此时你可以在项目的target中Build Phases页里 Link Binary With Libraries中看到有了libCorePlot-CocoaTouch.a.

  • 再到相应Target的 Build Settings页里,Other Linker Flags项中加上 -ObjC -all_load

  • 选择新项目的“info->Build”,在“Header Search Paths”中添加Core Plot头文件搜索路径,如:/Users/davidzhang/project/core-plot/framework。注意要选中“Recursive”小勾(英文原文中没有提这一点)。同时,在Other Linker Flags中要增加两个选项:-ObjC和-all_load(英文原文中遗漏了第2个选项)。

原文档的安装说明是:

Install Binaries for iOS

  1. Copy the CorePlotHeaders to your Xcode project

  2. Copy libCorePlotCocoaTouch.a to your Xcode project

  3. Add to Other Linker Flags in your target build settings:

-ObjC -all_load

  1. Add the QuartzCore framework to the project.

  2. Add a CPTGraph to your application. See the example apps in Source Code to see how, or read the documentation.

贴一下我的实例代码:

DetailViewController.h
1
2
3
4
5
6
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
@interface DetailsViewController : UIViewController<CPTPlotDataSource, CPTAxisDelegate>
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSMutableArray *dataArray;
@end
DetailViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#import "DetailsViewController.h"


@interface DetailsViewController ()

@end

@implementation DetailsViewController

@synthesize title,dataArray;

-(void)viewDidAppear:(BOOL)animated{
//初始化数组,并放入十个 0 - 20 间的随机数
self.dataArray = [[NSMutableArray alloc] init];
for(int i=0; i< 10; i++){
[self.dataArray addObject:[NSNumber numberWithInt:rand()%20]];
}

CGRect frame = CGRectMake(10,10, 300,100);

//图形要放在一个 CPTGraphHostingView 中,CPTGraphHostingView 继承自 UIView
CPTGraphHostingView *hostView = [[CPTGraphHostingView alloc] initWithFrame:frame];

//把 CPTGraphHostingView 加到你自己的 View 中
[self.view addSubview:hostView];
hostView.backgroundColor = [UIColor blueColor];

//在 CPTGraph 中画图,这里的 CPTXYGraph 是个曲线图
//要指定 CPTGraphHostingView 的 hostedGraph 属性来关联
CPTXYGraph *graph = [[CPTXYGraph alloc] initWithFrame:hostView.frame];
hostView.hostedGraph = graph;

CPTScatterPlot *scatterPlot = [[CPTScatterPlot alloc] initWithFrame:graph.bounds];
[graph addPlot:scatterPlot];
scatterPlot.dataSource = self; //设定数据源,需应用 CPTPlotDataSource 协议

//设置 PlotSpace,这里的 xRange 和 yRange 要理解好,它决定了点是否落在图形的可见区域
//location 值表示坐标起始值,一般可以设置元素中的最小值
//length 值表示从起始值上浮多少,一般可以用最大值减去最小值的结果
//其实我倒觉得,CPTPlotRange:(NSRange) range 好理解些,可以表示值从 0 到 20
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) scatterPlot.plotSpace;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0)
length:CPTDecimalFromFloat([self.dataArray count]-1)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0)
length:CPTDecimalFromFloat(20)];

//下面省去了坐标与线型及其他图形风格的代码
//
// [plotSpace release];
// [graph release];
// [hostView release];
}

//询问有多少个数据,在 CPTPlotDataSource 中声明的
- (NSUInteger) numberOfRecordsForPlot:(CPTPlot *)plot {
return [self.dataArray count];
}

//询问一个个数据值,在 CPTPlotDataSource 中声明的
- (NSNumber *) numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
if(fieldEnum == CPTScatterPlotFieldY){ //询问 Y 值时
return [self.dataArray objectAtIndex:index];
}else{ //询问 X 值时
return [NSNumber numberWithInt:index];
}
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(@"title = %@",self.title);
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

好多都是第三方的,自己闲麻烦,自己就整理了一套自己一个rss类,对需要的朋友给个帮助吧,也方便了自己,呵呵

直接贴代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
<?php
class Rss extends CController
{
//public
public $rss_ver = "2.0";
public $channel_title = '';
public $channel_link = '';
public $channel_description = '';
public $language = 'zh_CN';
public $copyright = '';
public $webMaster = '';
public $pubDate = '';
public $lastBuildDate = '';
public $generator = 'GoWhich RSS Generator';
public $content = '';
public $items = [];

/**
* 添加基本信息
* @param string $title
* @param string $link
* @param string $description
*/
public function __construct($title, $link, $description)
{
$this->channel_title = $title;
$this->channel_link = $link;
$this->channel_description = $description;
$this->pubDate = Date('Y-m-d H:i:s', time());
$this->lastBuildDate = Date('Y-m-d H:i:s', time());
}

/**
* 添加一个节点
* @param string $title
* @param string $link
* @param string $description
* @param date $pubDate
*/
public function addItem($title, $link, $description, $pubDate)
{
$this->items[] = ['title' => $title,
'link' => $link,
'descrīption' => $description,
'pubDate' => $pubDate];
}

/**
* 构建xml元素
*/
public function buildRSS()
{
$s = <<<RSS
<?xml version='1.0' encoding='utf-8'?>\n
<rss version="2.0">\n
RSS;

// start channel
$s .= "<channel>\n";
$s .= "<title><![CDATA[{$this->channel_title}]]></title>\n";
$s .= "<link><![CDATA[{$this->channel_link}]]></link>\n";
$s .= "<descrīption><![CDATA[{$this->channel_description}]]></descrīption>\n";
$s .= "<language>{$this->language}</language>\n";
if (!empty($this->copyright)) {
$s .= "<copyright><![CDATA[{$this->copyright}]]></copyright>\n";
}
if (!empty($this->webMaster)) {
$s .= "<webMaster><![CDATA[{$this->webMaster}]]></webMaster>\n";
}
if (!empty($this->pubDate)) {
$s .= "<pubDate>{$this->pubDate}</pubDate>\n";
}
if (!empty($this->lastBuildDate)) {
$s .= "<lastBuildDate>{$this->lastBuildDate}</lastBuildDate>\n";
}
if (!empty($this->generator)) {
$s .= "<generator>{$this->generator}</generator>\n";
}
// start items
for ($i = 0; $i < count($this->items); $i++) {
$s .= "<item>\n";
$s .= "<title><![CDATA[{$this->items[$i]['title']}]]></title>\n";
$s .= "<link><![CDATA[{$this->items[$i]['link']}]]></link>\n";
$s .= "<descrīption><![CDATA[{$this->items[$i]['descrīption']}]]></descrīption>\n";
$s .= "<pubDate>{$this->items[$i]['pubDate']}</pubDate>\n";
$s .= "</item>\n";
}
// close channel
$s .= "</channel>\n</rss>";
$this->content = $s;
}

/**
* 输出rss内容
*/
public function show()
{
if (empty($this->content)) {
$this->buildRSS();
}
return $this->content;
}

/**
* 设置版权
* @param unknown $copyright
*/
public function setCopyRight($copyright)
{
$this->copyright = $copyright;
}

/**
* 设置管理员
* @param unknown $master
*/
public function setWebMaster($master)
{
$this->webMaster = $master;
}

/**
* 设置发布时间
* @param date $date
*/
public function setpubDate($date)
{
$this->pubDate = $date;
}

/**
* 设置建立时间
* @param unknown $date
*/
public function setLastBuildDate($date)
{
$this->lastBuildDate = $date;
}

/**
* 将rss保存为文件
* @param String $fname
* @return boolean
*/
public function saveToFile($fname)
{
$handle = fopen($fname, 'wb');
if (false === $handle) {
return false;
}
fwrite($handle, $this->content);
fclose($handle);
}

/**
* 获取文件的内容
* @param String $fname
* @return boolean
*/
public function getFile($fname)
{
$handle = fopen($fname, 'r');
if (false === $handle) {
return false;
}
while (!feof($handle)) {
echo fgets($handle);
}
fclose($handle);
}
}

如果还是不都清楚可以到github上自己下载好了

github地址:https://github.com/zhangda89/php-library/blob/master/Rss.php

0%