在我的iOS应用程序中,我有一个类,它执行Web请求以获取位于mySQL DB中的一组信息。在这个类中,我有一个方法,它将mySQL查询作为输入:
- (NSMutableArray *) myreq:(NSString *)query{
// Create NSData object
NSData *dataQuery = [query
dataUsingEncoding:NSUTF8StringEncoding];
// Get NSString from NSData object in Base64
NSString *base64EncodedQuery = [dataQuery base64EncodedStringWithOptions:0];
// Print the Base64 encoded string
NSLog(@"Encoded: %@", base64EncodedQuery);
NSMutableString *strURL = [NSMutableString stringWithFormat:@"http://…=%@“,base64EncodedQuery];
[strURL setString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:dataURL
options:kNilOptions
error:&error];
NSMutableArray *results = [[NSMutableArray alloc] init];
int numRow = 0;
for (NSArray *arrow in json) {
[results addObjectsFromArray:arrow];
numRow++;
}
return results;
}
此方法向php脚本发送查询,该脚本立即执行此查询到MySQL DB并获取带有结果的json。我在这个方法中翻译json,最后返回一个包含结果的数组。 我在方法中调用myreq
- (void)downloadScope{
_arrID = [[NSMutableArray alloc] init];
_arrIDUsers = [[NSMutableArray alloc] init];
_arrUsernames = [[NSMutableArray alloc] init];
_arrPictures = [[NSMutableArray alloc] init];
[myQueue addOperation:[NSBlockOperation blockOperationWithBlock: ^{
query = @"SELECT ID FROM mytable”;
[_arrID addObjectsFromArray:[self myreq:query]];
for (int i = 0; i < [_arrID count]; i++) {
NSArray *tempArray = [[NSArray alloc] initWithArray:[self myreq:[NSString stringWithFormat:@"SELECT IDUsr,usrn, pictureaddress FROM mytable WHERE ID = %@",_arrID[i]]]];
[_arrIDUsers insertObject:tempArray[0] atIndex:i];
[_arrUsernames insertObject:tempArray[2] atIndex:i];
[_arrPictures insertObject:tempArray[2] atIndex:i];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.tableView reloadData];
}];
}
}]];
[myQueue setSuspended:NO];
}
在tableView中,我以这种方式创建单元格(使用SDWebImage):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Identificatore di cella
NSString *identifier = @“cellmy”;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
cell.backgroundColor = nil;
if ( cell == nil ) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
NSString *username = [self.arrUsernames objectAtIndex:indexPath.row];
UILabel *cellLabelUsername = (UILabel *)[cell viewWithTag:2];
cellLabelUsername.text = [username uppercaseString];
UIImageView *cellImageProfileSnap = (UIImageView *)[cell viewWithTag:5];
[cellImageProfileSnap sd_setImageWithURL:[NSURL URLWithString:[_arrPictures objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@“…”]];
}
在viewDidLoad中,我初始化了我的NSOperationQueue(在我的界面中定义):
myQueue = [[NSOperationQueue alloc] init];
[myQueue setMaxConcurrentOperationCount:100];
[myQueue setName:@"com.sada"];
我的目标是让一切更快,因为tableView中的加载速度很慢,我认为这不依赖于SDWebImage。请帮帮我