Я создаю приложение с загрузкой содержимого из файла PHP. У меня есть 4 просмотра с загрузкой контента из 4 разных файлов PHP. Для каждого контроллера представления я использую следующий код:
//
// turmaAViewController.m
// SamplePad
//
// Created by Mateus Nunes on 25/09/11.
// Copyright 2011 NBM Company. All rights reserved.
//
#import "turmaAViewController.h"
#import "DetailViewController.h"
@implementation turmaAViewController
@synthesize messageList;
@synthesize studentImageView;
@synthesize imageText;
//###############################################################################
//############################################################ DEVICE ORIENTATION
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
if(interfaceOrientation == UIInterfaceOrientationLandscapeRight){
return YES;
}
else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft){
return YES;
}else
return NO;
}
//##############################################################################################################################
//################# CUSTOM VIEW INITIALIZATION #################//
//##############################################################################################################################
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
lastId = 0;
chatParser = NULL;
}
return self;
}
//##############################################################################################################################
//################# DEALLOC - MEMORY RELEASE #################//
//##############################################################################################################################
-(void)dealloc {
[messageList release];
[super dealloc];
}
//##############################################################################################################################
//################# DISPLAY PHP FILE INTEGRATION #################//
//##############################################################################################################################
-(void)getNewMessages {
NSString *url = [NSString stringWithFormat:@"http://localhost/SPA/turmaa.php?past=%ld&t=%ld",lastId, time(0) ];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn){
receivedData = [[NSMutableData data] retain];
}else{}
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
//##############################################################################################################################
//################# FETCHING PRAGMAS #################//
//##############################################################################################################################
-(void)timerCallback {
[timer release];
[self getNewMessages];
}
//##############################################################################################################################
//################# CONNECTION PRAGMAS #################//
//##############################################################################################################################
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (chatParser)
[chatParser release];
if (messages == nil)
messages = [[NSMutableArray alloc] init];
chatParser = [[NSXMLParser alloc] initWithData:receivedData];
[chatParser setDelegate:self];
[chatParser parse];
[receivedData release];
[messageList reloadData];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector: @selector(timerCallback)]];
//[invocation setTarget:self];
[invocation setSelector:@selector(timerCallback)];
//timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO];
}
//##############################################################################################################################
//################# PARSING THE MESSAGE XML FILE LIST #################//
//##############################################################################################################################
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ( [elementName isEqualToString:@"message"] ) {
msgAdded = [[attributeDict objectForKey:@"added"] retain];
msgId = [[attributeDict objectForKey:@"id"] intValue];
msgAluno = [[NSMutableString alloc] init];
msgMatricula = [[NSMutableString alloc] init];
msgCpf = [[NSMutableString alloc] init];
msgImage = [[NSMutableString alloc] init];
msgCC = [[NSMutableString alloc] init];
inAluno = NO;
inMatricula = NO;
inCpf = NO;
inImage = NO;
inCC = NO;
}
if ( [elementName isEqualToString:@"aluno"] ) { inAluno = YES;}
if ( [elementName isEqualToString:@"matricula"] ) { inMatricula = YES;}
if ( [elementName isEqualToString:@"cpf"] ) { inCpf = YES;}
if ( [elementName isEqualToString:@"image"] ) { inImage = YES;}
if ( [elementName isEqualToString:@"CC"] ) { inCC = YES;}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ( inAluno ) { [msgAluno appendString:string]; }
if ( inMatricula ) { [msgMatricula appendString:string]; }
if ( inCpf ) { [msgCpf appendString:string]; }
if ( inImage ) { [msgImage appendString:string];}
if ( inCC ) { [msgCC appendString:string];}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ( [elementName isEqualToString:@"message"] ) {
[messages addObject:[NSDictionary dictionaryWithObjectsAndKeys:msgAdded,@"added",msgAluno,@"aluno",msgMatricula,@"matricula",msgCpf,@"cpf",msgImage,@"image",msgCC,@"CC",nil]];
[[messages reverseObjectEnumerator] allObjects];
lastId = msgId;
[msgAdded release];
[msgAluno release];
[msgMatricula release];
[msgCpf release];
[msgImage release];
[msgCC release];
}
if ( [elementName isEqualToString:@"aluno"] ) { inAluno = NO;}
if ( [elementName isEqualToString:@"matricula"] ) { inMatricula = NO;}
if ( [elementName isEqualToString:@"cpf"] ) { inCpf = NO;}
if ( [elementName isEqualToString:@"image"] ) { inImage = NO;}
if ( [elementName isEqualToString:@"CC"] ) { inCC = NO;}
}
//##############################################################################################################################
//################# PARSING FINISHED - START DISPLAYING #################//
//##############################################################################################################################
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection:(NSInteger)section {
return ( messages == nil ) ? 0 : [messages count];
}
-(UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"newsCustomCell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"newsCustomCell" owner:self options:nil];
cell = (UITableViewCell *)[nib objectAtIndex:0];
}
NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
UILabel *timeDate = (UILabel *)[cell viewWithTag:1];
timeDate.text = [itemAtIndex objectForKey:@"added"];
UILabel *userL = (UILabel *)[cell viewWithTag:2];
userL.text = [itemAtIndex objectForKey:@"aluno"];
UILabel *textL = (UILabel *)[cell viewWithTag:3];
textL.text = [itemAtIndex objectForKey:@"matricula"];
UILabel *textL2 = (UILabel *)[cell viewWithTag:4];
textL2.text = [itemAtIndex objectForKey:@"cpf"];
UILabel *imageL = (UILabel *)[cell viewWithTag:5];
imageL.text = [itemAtIndex objectForKey:@"image"];
UILabel *videoL = (UILabel *)[cell viewWithTag:6];
videoL.text = [itemAtIndex objectForKey:@"CC"];
UIWebView *webView = (UIWebView *) [cell viewWithTag:7];
NSString *urlAddress = [itemAtIndex objectForKey:@"image"];
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
NSString *selectTime = [itemAtIndex objectForKey:@"added"];
NSString *selectUser = [itemAtIndex objectForKey:@"aluno"];
NSString *selectMessage = [itemAtIndex objectForKey:@"matricula"];
NSString *selectMessage2 = [itemAtIndex objectForKey:@"cpf"];
NSString *selectImage = [itemAtIndex objectForKey:@"image"];
NSString *selectVideo = [itemAtIndex objectForKey:@"CC"];
dvController.selectedTime = selectTime;
dvController.selectedUser = selectUser;
dvController.selectedImage = selectImage;
dvController.selectedMessage = selectMessage;
dvController.selectedMessage2 = selectMessage2;
dvController.selectedVideo = selectVideo;
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
dvController = nil;
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
//##############################################################################################################################
//################# PARSING FINISHED - START DISPLAYING #################//
//##############################################################################################################################
-(void)viewDidLoad {
messageList.dataSource = self;
messageList.delegate = self;
[messageList release];
[self getNewMessages];
[super viewDidLoad];
}
@end
Во-первых, когда я построил одно представление с этим кодом и протестировал его, оно работало хорошо, никаких проблем. Но когда я добавил этот код в другие представления, приложение начало падать, ошибка «EXC_BAD_ACCESS»! Из-за этого я полагаю, что мне нужно убить запрос, когда у меня закончится видение, но как я могу это сделать или если вы обнаружили другую проблему!