Gowhich

Durban's Blog

在PC上监测web页面的HTTP请求是一件非常简单的事,我们有大量的软件可以来做,甚至浏览器就自带了有这样功能的开发插件。但是在移动设备上就没那么简单了,没有软件,权限控制……下面将介绍2种监测移动设备HTTP请求的方式。

使用Charles

在连上WIFI的前提下,android和ios设备都可以通过Charles来监测HTTP请求,原理是通过Charles在PC上架设一个代理,手机访问这个代理,Charles记录网络请求。ios设备,在“设置”-“无线局域网络”里可以直接设置代理,而android没有设置代理的功能,需要取得root权限后安装第三方软件来实现。

操作步骤:
下载Charles(http://www.charlesproxy.com/download/),安装完成后打开软件
通过菜单上的“Proxy”-“Proxy Settings…”,进入代理设置见面
“Port”填默认的“8888”即可,勾选“Enable transparent HTTP proxying”,点“OK”确认
设置手机的代理,端口(Port)写Charles中的端口设置,即“8888”,IP填你PC的IP地址
用手机发起任意HTTP请求,Charles会弹出一个提示框,点“Allow”,好了HTTP请求都出现在Charles里了

全选所有请求,并选择右侧的“Chart”选项卡就能看到整个HTTP请求瀑布图了:

Android手机设置代理的方式:
安装“z4root”软件,进入软件后选择第二项,等待一段时间后,自动重启,取得root权限完成
安装“Transparent Proxy”,进入“Proxy Host”设置PC的IP地址,进入“Proxy Port”设置端口号,即“8888”,勾选“Proxy”,设置完成

使用TCPDUMP和Wireshark

Android手机,可以使用TCPDUMP输出网络请求的LOG文件,然后用Wireshark打开该文件,进行统计分析。

操作步骤:
下载TCPDUMP(http://www.strazzere.com/android/tcpdump),放到D根目录盘下
下载安装Wireshark(http://www.wireshark.org/)
root手机,方法如上所述
用usb连上手机
打开命令行工具CMD,依次输入如下命令:
adb push d:\tcpdump /data/local/tcpdump
adb shell chmod 6755 /data/local/tcpdump
adb shell tcpdump -p -vv -s 0 -w /sdcard/capture.pcap -Z root
停止抓包:按Ctrl+c
导出抓包得到的文件到d盘根目录:adb pull /sdcard/capture.pcap d:/
双击capture.pcap文件,wireshark启动

参考:http://www.zhouqicf.com/others/mobile-network-requests-monitor

一开始不知如何在iphone里设置代理,网上说的大部分都是设置vpn的并不是代理设置。功夫不负有心人,在换了不同的关键字查找,终于找到设置方法了!其实很简单,步骤如下:
1,连上wifi

2,在 设置=>Wi-Fi=>你连上的网络右边的小箭头 然后往下拉有http代理设置这一栏,选择手动,然后输入你的代理服务器地址或者域名以及端口!

匹配9-15个由字母/数字组成的字符串的正则表达式:

1
2
3
NSString * regex = @"^[A-Za-z0-9]{9,15}$";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
BOOL isMatch = [pred evaluateWithObject:txtfldPhoneNumber.text];

Cocoa用NSPredicate描述查询的方式,原理类似于在数据库中进行查询

用BETWEEN,IN,BEGINWITH,ENDWITH,CONTAINS,LIKE这些谓词来构造NSPredicate,必要的时候使用SELF直接对自己进行匹配
基本的查询

1
2
3
4
5
6
7
8
9
10
11
12
NSPredicate *predicate; 
predicate = [NSPredicate predicateWithFormat: @"name == 'Herbie'"];
BOOL match = [predicate evaluateWithObject: car];
NSLog (@"%s", (match) ? "YES" : "NO");
//在整个cars里面循环比较
predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"];
NSArray *cars = [garage cars];
for (Car *car in [garage cars]) {
if ([predicate evaluateWithObject: car]) {
NSLog (@"%@", car.name);
}
}

输出完整的信息

1
2
3
4
5
6
7
8
9
10
11
12
predicate = [NSPredicate predicateWithFormat: @"engine.horsepower > 150"]; 
NSArray *results;
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);
//含有变量的谓词
NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat:@"name == $NAME"];
NSDictionary *varDict;
varDict = [NSDictionary dictionaryWithObjectsAndKeys: @"Herbie", @"NAME", nil];
predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];
NSLog(@"SNORGLE: %@", predicate);
match = [predicate evaluateWithObject: car];
NSLog (@"%s", (match) ? "YES" : "NO");

注意不能使用$VARIABLE作为路径名,因为它值代表值

1
2
3
4
5
6
7
8
9
10
11
//谓词字符串还支持c语言中一些常用的运算符  
predicate = [NSPredicate predicateWithFormat: @"(engine.horsepower > 50) AND (engine.horsepower < 200)"];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"oop %@", results);
predicate = [NSPredicate predicateWithFormat: @"name < 'Newton'"];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", [results valueForKey: @"name"]);
//强大的数组运算符
predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN { 50, 200 }"];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);
1
2
3
4
5
6
7
8
9
10
NSArray *betweens = [NSArray arrayWithObjects: 
[NSNumber numberWithInt: 50], [NSNumber numberWithInt: 200], nil];
predicate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN %@", betweens];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);
predicateTemplate = [NSPredicate predicateWithFormat: @"engine.horsepower BETWEEN $POWERS"];
varDict = [NSDictionary dictionaryWithObjectsAndKeys: betweens, @"POWERS", nil];
predicate = [predicateTemplate predicateWithSubstitutionVariables: varDict];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);
1
2
3
4
5
6
7
//IN运算符  
predicate = [NSPredicate predicateWithFormat: @"name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", [results valueForKey: @"name"]);
predicate = [NSPredicate predicateWithFormat: @"SELF.name IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", [results valueForKey: @"name"]);
1
2
3
4
5
6
7
8
9
names = [cars valueForKey: @"name"]; 
predicate = [NSPredicate predicateWithFormat: @"SELF IN { 'Herbie', 'Snugs', 'Badger', 'Flap' }"];
results = [names filteredArrayUsingPredicate: predicate];//这里限制了SELF的范围
NSLog (@"%@", results);
//BEGINSWITH,ENDSWITH,CONTAINS
//附加符号,[c],[d],[cd],c表示不区分大小写,d表示不区分发音字符,cd表示什么都不区分
predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'Bad'"];
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);
1
2
3
predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH 'HERB'"]; 
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);
1
2
3
predicate = [NSPredicate predicateWithFormat: @"name BEGINSWITH[cd] 'HERB'"]; 
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);

LIKE运算符(通配符)

1
2
3
predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '*er*'"]; 
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);
1
2
3
predicate = [NSPredicate predicateWithFormat: @"name LIKE[cd] '???er*'"]; 
results = [cars filteredArrayUsingPredicate: predicate];
NSLog (@"%@", results);

参考资料:http://www.2cto.com/kf/201208/150608.html

很多情况需要从网络上加载图片,然后将图片在imageview中显示出来,但每次都要从网络上请求,会严重影响用户体验,为了不是每次显示都需要从网上下载数据,希望将图片放到本地缓存,因此我们需要一个好的的缓存策略,今天我将我在项目工程中的实际经验分享给大家,我这里主要介绍一下强大的ASIHTTPRequest的缓存策略,以及使用方法:

下面是具体步骤:
一、设置缓存策略
首先在SplitDemoAppDelegate委托代理中,实现如下代码:
在SplitDemoAppDelegate.h文件中,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#import <UIKit/UIKit.h>
@class ASIDownloadCache;

@interface SplitDemoAppDelegate : NSObject <UIApplicationDelegate,UITabBarControllerDelegate> {

UIWindow *_window;

ASIDownloadCache*_downloadCache; //下载缓存策略

}

@property (nonatomic, retain) ASIDownloadCache*downloadCache;

@end

在SplitDemoAppDelegate.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
#import "SplitDemoAppDelegate.h"

@implementation SplitDemoAppDelegate

@synthesize window=_window;

@synthesize downloadCache = _downloadCache;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions

{

//初始化ASIDownloadCache缓存对象

ASIDownloadCache *cache = [[ASIDownloadCache alloc] init];

self.downloadCache = cache;

[cache release];

//路径

NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *documentDirectory = [paths objectAtIndex:0];

//设置缓存存放路径

[self.downloadCache setStoragePath:[documentDirectorystringByAppendingPathComponent:@"resource"]];

//设置缓存策略

[self.downloadCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];

// Override point for customization after application launch.

[self.window makeKeyAndVisible];

return YES;

}


- (void)dealloc

{

[_window release];

[_downloadCache release];

[super dealloc];

}
@end

二、创建缓存线程

这一步是创建一个NSOperation类,实现缓存的方法,代码如下:

ResourceContainer.h文件实现

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
#import <Foundation/Foundation.h>

#import "ASIHTTPRequest.h"

#import "SplitDemoAppDelegate.h"

@interface ResourceContainer : NSOperation {

NSURL*_resourceURL; //资源请求url

NSObject*_hostObject;

SEL_resourceDidReceive; //资源接手响应方法

SplitDemoAppDelegate*_appDelegate; //应用委托对象

ASIHTTPRequest*_httpRequest;

UIImageView*_imageView;

}

@property (nonatomic, retain) NSURL*resourceURL;

@property (nonatomic, retain) NSObject*hostObject;

@property (nonatomic, assign) SELresourceDidReceive;

@property (nonatomic, assign) SplitDemoAppDelegate *appDelegate;

@property (nonatomic, retain) ASIHTTPRequest*httpRequest;

@property (nonatomic, retain) UIImageView*imageView;

//http请求回调方法

-(void)didStartHttpRequest:(ASIHTTPRequest *)request;

-(void)didFinishHttpRequest:(ASIHTTPRequest *)request;

-(void)didFailedHttpRequest:(ASIHTTPRequest *)request;

//取消资源请求

-(void)cancelReourceGet;

//资源接收回调方法

-(void)resourceDidReceive:(NSData *)resource;

@end

ResourceContainer.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
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
#import "ResourceContainer.h"
#import "HttpConstant.h"
#import "ASIDownloadCache.h"
@implementation ResourceContainer
@synthesize resourceURL = _resourceURL;
@synthesize hostObject = _hostObject;
@synthesize resourceDidReceive = _resourceDidReceive;
@synthesize appDelegate = _appDelegate;
@synthesize httpRequest = _httpRequest;
@synthesize imageView = _imageView;

-(id)init{

if(self == [super init]){
self.appDelegate = (SplitDemoAppDelegate *)[[UIApplication sharedApplication] delegate];
}
return self;
}


-(void)main{

if(self.hostObject == nil)
return;

if(self.resourceURL == nil){
[self resourceDidReceive:nil];
return;
}

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:self.resourceURL]
self.httpRequest = request;



[self.httpRequest setDownloadCache:self.appDelegate.downloadCache];
[self.httpRequest setDelegate:self];
[self.httpRequest setDidStartSelector:@selector(didStartHttpRequest:)];
[self.httpRequest setDidFinishSelector:@selector(didFinishHttpRequest:)];
[self.httpRequest setDidFailSelector:@selector(didFailedHttpRequest:)];

//发异步请求

[self.httpRequest startAsynchronous];

}

- (void)dealloc {

[_resourceURL release];
[_hostObject release];
[_httpRequest release];
[_imageView release];
[super dealloc];

}

//开始请求

-(void)didStartHttpRequest:(ASIHTTPRequest *)request{

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

}

//请求成功返回处理结果

-(void)didFinishHttpRequest:(ASIHTTPRequest *)request{

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

if([request responseStatusCode] == 200 || [request responseStatusCode] == 304){

//判断是否来自缓存

if([request didUseCachedResponse]){
NSLog(@"=========资源请求:%@ 来自缓存============",[self.resourceURL absoluteURL]);
}
else{
NSLog(@"=========资源请求:图片不来自缓存============");
}
[self resourceDidReceive:[request responseData]];

}
else
{

[self resourceDidReceive:nil];

}

}

//失败请求返回处理结果

-(void)didFailedHttpRequest:(ASIHTTPRequest *)request{

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

[self resourceDidReceive:nil];

}

//取消资源请求

-(void)cancelReourceGet{

[self.httpRequest cancel];

}

//资源接收处理方法

-(void)resourceDidReceive:(NSData *)resource{

if([self.hostObject respondsToSelector:self.resourceDidReceive]){

if(resource != nil && self.imageView != nil){

self.imageView.image = [UIImage imageWithData:resource];

}

[self.hostObject performSelectorOnMainThread:self.resourceDidReceive withObject:self.imageViewwaitUntilDone:NO];

}

}
@end

到第二步,我们的缓存策略的设置,以及资源请求和接收数据方法已经构建完毕,下面介绍一下如何使用我们上面创建的NSOperation类
三、图片请求(利用上面创建的类)
这里以我的工程为例进行分析:
在DetailViewController.h声明文件中:

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
#import <UIKit/UIKit.h>

@interface DetailViewController :UIViewController {

NSURL *_imageURL; //图片url

NSMutableArray *_originalIndexArray; //保存请求图片的号

NSMutableDictionary *_originalOperationDic; //保存图片请求队列

NSOperationQueue *_requestImageQueue; //图片请求队列

}

@property (nonatomic, retain) NSURL *imageURL;
@property (nonatomic, retain) NSMutableArray *originalIndexArray;
@property (nonatomic, retain) NSMutableDictionary *originalOperationDic;
@property (nonatomic, retain) NSOperationQueue * requestImageQueue;

//显示图片信息

-(void)displayProductImage;

//根据图片序号显示请求图片资源

-(void)displayImageByIndex:(NSInteger)index ByImageURL:(NSURL *)url;

//处理图片请求返回信息

-(void)imageDidReceive:(UIImageView *)imageView;

@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
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
#import "ProductDetailViewController.h"
//这里引入在第二步中,我们创建的对象
#import "ResourceContainer.h"

@implementation DetailViewController
@synthesize imageURL = _imageURL;
@synthesize originalIndexArray = _originalIndexArray;
@synthesize originalOperationDic = _originalOperationDic;
@synthesize requestImageQueue = _requestImageQueue;


- (void)viewDidLoad
{

[super viewDidLoad];
NSOperationQueue *tempQueue = [[NSOperationQueue alloc] init];

self.requsetImageQueue = tempQueue;
[tempQueue release];

NSMutableArray *array = [[NSMutableArray alloc] init];

self.originalIndexArray = array;
[array release];

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

self.originalOperationDic = dic;
[dic release];

}

//显示图片信息

-(void)displayProductImage
{
NSURL *url = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx"];

//这个是从器返回有图片数目,self.xxxx根据具体的场合

int imageCount = [self.xxxx.imageNum intValue];

for (int i=0; i<imageCount; i++) {

NSString *str1 = @"这里是拼图片请求url,根据实际需求";

self.imageURL = [url URLByAppendingPathComponent:str1];

//根据图片号请求资源

[self displayImageByIndex:i ByImageURL:self.productImageURL];

}

}

//根据图片序号显示请求图片资源

-(void) displayImageByIndex:(NSInteger)index ByImageURL:(NSURL *)url

{

NSString *indexForString = [NSString stringWithFormat:@"%d",index];

//若数组中已经存在该图片编号,说明图片加载完毕,直接返回

if ([self.originalIndexArray containsObject:indexForString]) {

return;

}

//创建UIImageView对象

UIImageView *imageView = [[UIImageView alloc] init];

imageView.tag = index;

//创建资源请求对象

ResourceContainer *imageOperation = [[ResourceContainer alloc] init];

imageOperation.resourceURL = url;

imageOperation.hostObject = self;

//设置收到图片信息处理理方法

imageOperation.resourceDidReceive = @selector(imageDidReceive:);

imageOperation.imageView = imageView;

[imageView release];

//将图片请求对象加入图片请求队列中

[self.requsetImageQueue addOperation:imageOperation];

[self.originalOperationDic setObject:imageOperation forKey:indexForString];

[imageOperation release];

}

//处理图片请求返回信息

-(void)imageDidReceive:(UIImageView *)imageView
{

if (imageView == nil||imageView.image == nil) {
imageView.image = [UIImage imageNamed:@"no-pic-300-250.png"];
}
//将图片信息加载到前台,self.openFlowView是我用的coverFlow,coverFlow的使用方法网上很多,自己找吧

[self.openFlowView setImage:imageView.image forIndex:imageView.tag];

[self.originalIndexArray addObject:[NSString stringWithFormat:@"%d",imageView.tag]];

[self.originalOperationDic removeObjectForKey:[NSString stringWithFormat:@"%d",imageView.tag]];
}

- (void)dealloc
{
[_requestImageQueue release];

[_originalIndexArray release];

[_originalOperationDic release];

[_imageURL release];

[super dealloc];
}

@end

经过上述步骤,我们实现了加载网络图片时缓存功能,增强了用户体验效果。
参考:http://www.cnblogs.com/pengyingh/articles/2343061.html

首先要知道你是如何处理使得UISearchBar失去焦点的,那么我的办法一会你可以看一下,同时还有一个问题解决,就是如何是的CancelButton不失去操作的功能:

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-(void) scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
[self.personSearch resignFirstResponder];

self.personSearch.showsCancelButton=YES;
for(id control in [self.personSearch subviews])
{
if ([control isKindOfClass:[UIButton class]])
{
UIButton * btn =(UIButton *)control;
[btn setTitle:@"取消" forState:UIControlStateNormal ];
btn.enabled=YES;
}
}
}

虽然说这样的效率不好,但是既然有这样的方式就有这种方式存在的道理

我记录一下其实现方法:

1
cell.imageViewPic.image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"personpanel-%@-zfx.jpg",[dic valueForKey:@"person_id"]] relativeToURL:[NSURL URLWithString:@"http://xxxx.xxxx.xxxxx/xxxx/"]]]];

cell.imageViewPic是一个实例化的UIImageview

使用RegexKitLite正则表达式需要以下工作:
1.RegexKitLite官方网址(内含使用教程):http://regexkit.sourceforge.net/RegexKitLite
2.下载地址:http://downloads.sourceforge.net/regexkit/RegexKitLite-4.0.tar.bz2
3.将RegexKitLite.h和RegexKitLite.m引入到工程中。
4.引入”libicucore.dylib”框架
5.需要在处理的类中导入”RegexKitLite.h”

言归正传,用正则表达式提取匹配的内容(此例子中讲述匹配字符串中的手机号码):

1
2
3
4
5
NSString *searchString = @"15200000000,1234,12012345678,13400000000"; // 要提取的字符串
NSString *regexString = @"\\b(13|15|18)([0-9]{9})\\b"; // 手机号码的正则表达式(由于15和18号段的不太熟悉,索性就干脆都算上了,你懂的。)
NSArray *matchArray = [searchString componentsMatchedByRegex:regexString]; // 匹配结果以数组形式返回
NSLog(@"%@",matchArray); // 进行输出
NSLog(@"%@",matchArray);

输出结果如下:

1
2
3
4
2011-08-23 14:39:23.356 ZQRegex[6726:207] (
15200000000,
13400000000
)

通过setTitle和titleEdgeInsets,setImage和imageEdgeInsets,能够实现title和image位置的变化

具体的代码我以实现title的位置变化为例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
addButton.layer.borderColor = [[UIColor whiteColor] CGColor];
addButton.layer.borderWidth = 2.0;
addButton.layer.cornerRadius = 10.0;
addButton.titleLabel.font = [UIFont systemFontOfSize:54.0];
addButton.titleLabel.textAlignment = NSTextAlignmentCenter;
[addButton sizeToFit];
[addButton setTitleEdgeInsets:UIEdgeInsetsMake(-10.0, 0.0, 0.0, 0.0)];
[addButton setFrame:CGRectMake(0.0, 5.0, 60.0, 60.0)];
[addButton setTitle:@"+" forState:UIControlStateNormal];
[addButton addTarget:self
action:@selector(addAction:)
forControlEvents:UIControlEventTouchUpInside];

看了几个实例,最终解决了这个问题,之间为什么老是有问题没有解决呢,原因我觉得是跟ARC有关,因为我的应用是使用ARC的然后将下载回来的代码进行了调整,将release的代码段去掉了。结果有了一些问题,也不是很了解具体是哪里。目前问题解决了,里面使用了关于ARC机制和非ARC机制共存的办法,详细的内容可以参考我的这篇文章iOS 开发,工程中混合使用 ARC 和非ARC

代码段贴一下好了:

EGOTableViewPullRefresh的下载地址:http://vdisk.weibo.com/s/FtH88

indexViewController.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//
// indexViewController.h
// index
//
// Created by david on 13-6-8.
// Copyright (c) 2013年 walkerfree. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "EGORefreshTableHeaderView.h"

@interface indexViewController : UIViewController<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, EGORefreshTableHeaderDelegate>
{
EGORefreshTableHeaderView *_refreshHeaderView;
BOOL _reloading;
}
@property (strong, nonatomic) IBOutlet UISearchBar *personSearch;
@property (strong, nonatomic) IBOutlet UITableView *dataTable;
@property (strong, nonatomic) NSMutableDictionary *dataDic;

-(void) initPersonIndexListData;
@end

indexViewController.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
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//
// indexViewController.m
// index
//
// Created by david on 13-6-8.
// Copyright (c) 2013年 walkerfree. All rights reserved.
//

#import "indexViewController.h"
#import "personIndexTrendViewController.h"
#import "listCell.h"

@interface indexViewController ()

@end

@implementation indexViewController

@synthesize personSearch = _personSearch;
@synthesize dataTable = _dataTable;
@synthesize dataDic = _dataDic;

- (void)viewDidLoad
{
[super viewDidLoad];
[self initPersonIndexListData];
self.dataTable.delegate = self;
self.dataTable.dataSource = self;

if (_refreshHeaderView == nil) {
//初始化下拉刷新控件
_refreshHeaderView = [[EGORefreshTableHeaderView alloc] init];
_refreshHeaderView.delegate = self;
//将下拉刷新控件作为子控件添加到UITableView中
[self.dataTable addSubview:_refreshHeaderView];
}


[_refreshHeaderView refreshLastUpdatedDate];

}

-(void) startLoadingTableViewData
{
[self initPersonIndexListData];
_reloading = YES;
}

-(void) endLoadingTableViewData
{
_reloading = NO;
[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.dataTable];
// NSLog(@"done");
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

-(void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
-(void) egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
[self startLoadingTableViewData];
[self performSelector:@selector(endLoadingTableViewData) withObject:nil afterDelay:3.0];
}

-(BOOL) egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
return _reloading;
}

-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
return [NSDate date];
}



-(void) viewWillDisappear:(BOOL)animated
{
UIBarButtonItem *returnBarItem = [[UIBarButtonItem alloc] init];
returnBarItem.title = @"返回";
self.navigationItem.backBarButtonItem = returnBarItem;
}

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

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

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

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *listCellIdentifier = @"listCell";

UINib *nib = [UINib nibWithNibName:@"listCell" bundle:nil];
[self.dataTable registerNib:nib forCellReuseIdentifier:listCellIdentifier];

listCell *cell = [tableView dequeueReusableCellWithIdentifier:listCellIdentifier];
if(cell == nil){
cell = [[listCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:listCellIdentifier];

}

NSDictionary *dic = [self.dataDic objectForKey:[NSString stringWithFormat:@"%d",[indexPath row]]];

cell.personRank.text = [NSString stringWithFormat:@"%d",[indexPath row] + 1];
cell.personName.text = [dic valueForKey:@"zh_name"];
cell.personIndex.text = [NSString stringWithFormat:@"艺人新媒体指数 %0.2f",[[dic valueForKey:@"score"] floatValue]];
cell.personIndex.font = [UIFont systemFontOfSize:14.0];
cell.personIndex.textColor = [UIColor lightGrayColor];

if([[NSString stringWithFormat:@"%u",[indexPath row]] isEqualToString:@"0"])
{
cell.personRank.backgroundColor = [UIColor greenColor];
}
else
{
cell.personRank.backgroundColor = [UIColor lightGrayColor];
}

if([[NSString stringWithFormat:@"%u",[indexPath row]] isEqualToString:@"1"])
{
cell.personRank.backgroundColor = [UIColor greenColor];
}

if([[NSString stringWithFormat:@"%u",[indexPath row]] isEqualToString:@"2"])
{
cell.personRank.backgroundColor = [UIColor greenColor];
}



cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dic = [self.dataDic valueForKey:[NSString stringWithFormat:@"%u",[indexPath row]]];
personIndexTrendViewController *trend = [[personIndexTrendViewController alloc] initWithNibName:@"personIndexTrendViewController"
bundle:nil];
trend.personInfo = [dic mutableCopy];
[self.navigationController pushViewController:trend animated:YES];

}

#pragma UISearchBar


#pragma 自定义函数
-(void)initPersonIndexListData
{
NSLog(@"加载数据");
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSDate *date = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSString *dateString = [dateFormatter stringFromDate: [NSDate dateWithTimeInterval:-(2 * 24 * 60 * 60) sinceDate:date]];

NSString *urlString = @"http://XXXXXXXXX.XXX.XXX.XXX?";

NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];

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

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

if(receivedData == nil)
{
NSLog(@"获取数据失败");
}
else
{
NSError *jsonError = [[NSError alloc] init];
NSDictionary *personDictionary = [NSJSONSerialization JSONObjectWithData:receivedData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSMutableDictionary *personInfo = [personDictionary objectForKey:@"data"];

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

self.dataDic = [NSMutableDictionary dictionaryWithCapacity:20];

if([personList isKindOfClass:[NSMutableArray class]])
{
int i = 0;
for (NSDictionary *dic in personList) {
[self.dataDic setObject:dic forKey:[NSString stringWithFormat:@"%d",i]];
i++;
}
}



if([personList isKindOfClass:[NSMutableDictionary class]])
{
NSLog(@"NSMutableDictionary 类");
}

if([self.dataDic count] > 0)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
}
@end

问题是这样的:

在项目开发过程中我们通常会用到第三方提供的源代码,麻烦的是有些开源项目用的是 ARC,有的用的是非 ARC。
我在使用 SVProgressHUD 做等待视图时遇到问题,最终发现该项目使用的是 ARC 模式,而我的工程使用的是非 ARC 模式。

解决方法是这样的:

Xcode 项目中我们可以使用 ARC 和非 ARC 的混合模式。
如果你的项目使用的非 ARC 模式,则为 ARC 模式的代码文件加入 -fobjc-arc 标签。
如果你的项目使用的是 ARC 模式,则为非 ARC 模式的代码文件加入 -fno-objc-arc 标签。
添加标签的方法:
1,打开:你的target -> Build Phases -> Compile Sources.
2,双击对应的 *.m 文件
3,在弹出窗口中输入上面提到的标签 -fobjc-arc / -fno-objc-arc
4,点击 done 保存

参考:http://blog.csdn.net/fangzhangsc2006/article/details/8049765#reply

0%