Возвращенные данные веб-службы не заполняют табличное представление - PullRequest
0 голосов
/ 01 февраля 2011

Эй, я не могу понять, почему этот код не работает? Я пытаюсь добавить свои возвращенные данные из веб-службы в uitableview, но безуспешно. Таблица отображается пустой каждый раз. Кажется, ему не нравится метод cellForRowAtIndexPath. Но, честно говоря, я не уверен. Я не могу определить это ни за что. Пожалуйста помоги. Спасибо!

#import "RSSTableViewController.h"


@implementation RSSTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
 if (self = [super initWithStyle:style]) {
    songs = [[NSMutableArray alloc] init];
}
return self;
}



- (void)loadSongs
{

 [songs removeAllObjects];
[[self tableView] reloadData];

// Construct the web service URL
NSURL *url =[NSURL URLWithString:@"http://localhost/get_params"];

NSURLRequest *request = [NSURLRequest requestWithURL:url
                                         cachePolicy:NSURLRequestReloadIgnoringCacheData
                                     timeoutInterval:30];

if (connectionInProgress) {
    [connectionInProgress cancel];
    [connectionInProgress release];
}

[xmlData release];
xmlData = [[NSMutableData alloc] init];

connectionInProgress = [[NSURLConnection alloc] initWithRequest:request
                                                       delegate:self];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadSongs];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[xmlData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];

NSString *responseString = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];

songs = [responseString componentsSeparatedByString:@","];

newSongs = [[NSMutableArray alloc] init];

for(int i=0; i < [songs count]; i++) {
    [newSongs addObject:[songs:i]]);
}
     [songs autorelease];


[[self tableView] reloadData];
// 
}

- (void)connection:(NSURLConnection *)connection 
  didFailWithError:(NSError *)error
{
    [connectionInProgress release];
    connectionInProgress = nil;

    [xmlData release];
    xmlData = nil;

    NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@",
                         [error localizedDescription]];
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:errorString
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                              destructiveButtonTitle:nil
                                                  otherButtonTitles:nil];
    [actionSheet showInView:[[self view] window]];
    [actionSheet autorelease];

    [[self tableView] reloadData];
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];

}


- (void)dealloc {
    [super dealloc];
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return [newSongs count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *cell = [tableView     dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
                 initWithStyle:UITableViewCellStyleDefault
                 reuseIdentifier:@"UITableViewCell"] autorelease];
    }

    [[cell textLabel] setText:[newSongs objectAtIndex:[indexPath row]]];



    return cell;
}

@end

1 Ответ

2 голосов
/ 01 февраля 2011

Похоже, вы игнорируете предупреждающие сообщения, что в Objective-C запрещено.Следующий код не может работать:

[newSongs addObject:[songs:i]]

То, что вы, вероятно, хотели написать, было примерно так:

[newSongs addObject:[songs objectAtIndex:i]]

Но вместо того, чтобы делать все это:

newSongs = [[NSMutableArray alloc] init];

for(int i=0; i < [songs count]; i++) {
    [newSongs addObject:[songs:i]]);
}

почему бы просто не сделать это?

newSongs = [songs mutableCopy];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...