Данные JSON в массиве NSMutable находятся вне области видимости, и tableView не будет отображать cellData - PullRequest
0 голосов
/ 15 августа 2010

Итак, я работаю над приложением для iphone, которое анализирует json и пытается представить результаты в простом UITableview. У меня есть настройки tableview в xib-файле, а также источник данных и делегат как MainViewController (это служебное приложение). Я получаю JSON-запрос очень хорошо, и я всегда проверяю это, выводя его в текстовую метку. Но когда я отлаживаю и наводю курсор на переменную cellData var (которая содержит эти данные), она выходит из области видимости, и мой симулятор показывает пустую таблицу, которая не будет прокручиваться ... как будто она застряла в ожидании чего-то, чтобы закончить.

Вот мой заголовок для контроллера вида:

#import "FlipsideViewController.h"

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate,     UITableViewDelegate, UITableViewDataSource> {
IBOutlet UILabel *label;
UITableView *theTableView;
NSMutableArray *cellData;

}
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (retain) NSMutableArray *cellData;
- (IBAction)showInfo:(id)sender;

@end

и вот моя реализация:

#import "MainViewController.h"
#import "JSON.h"


@implementation MainViewController
@synthesize label;
@synthesize cellData;
//Begin code for Table View Data Source (required methods)

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //how many rows in the section; for testing purposes...placed here
    return [cellData count];
    //return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //create a cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];     
    }

    //fill it with contents
    cell.textLabel.text = [cellData objectAtIndex:indexPath.row];
    //return it
    return cell;
}

//End code for Table View Data Source

//Begin code for JSON stuffs

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

    //TODO: need to extract this code out to a function because need to make multiple requests per run of the app....
    //responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://tabular.heroku.com/tab_stores/tester.json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    cellData = [[NSMutableArray alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{

    NSMutableData *mutData = [[NSMutableData alloc] init];
    [mutData appendData:data];

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

    NSArray *responseData = [responseString JSONValue];

    NSMutableString *text = [NSMutableString stringWithString:@"T:"];

    for (int i = 0; i < [responseData count]; i++)
        [text appendFormat:@"%@\n", [responseData objectAtIndex:i]];

    label.text =  text;

    NSLog(@"%@\n", cellData);
    //Let's parse the data the way its supposed to be

    //for every window, there should be a section.
    for (int i=0; i<[responseData count]; i++) {
        //manage table section
        //maybe print window 1

    }


    //[cellData addObject:[responseData objectAtIndex:0]];
    [cellData addObjectsFromArray:responseData];
//  [responseData release];
    NSLog(@"%@\n", cellData);


    [theTableView reloadData];

    [responseString release];
    [mutData release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}

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

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

    //[responseData release];

    //cellData = [responseString JSONValue];

    //NSLog(@"this is in tabs %@", tabs);
//  NSLog(@"this is in cellData %@", cellData);
//      NSLog(@"this is in cellDatas %@", cellDatas);

    //NSMutableString *text = [NSMutableString stringWithString:@"T:"];

//  for (int i = 0; i < [cellDatas count]; i++)
//      [text appendFormat:@"%@\n", [cellDatas objectAtIndex:i]];

//  label.text =  text;

    //[theTableView reloadData];
}


//End code for JSON stuffs

.
.
.

- (void)dealloc 
{
  [theTableView release];
//[cellData release];
  [super dealloc];
}

Я знаю, что tableview сначала вызывает эти функции для числа sectioniInTableView и numberOfRowsInSection, поэтому он не получает данные, но потом я подумал, что вызов reloadData будет работать ... но ничего. Кто-нибудь может помочь новичку?

* NSLogs в консоли:

2010-08-15 15:42:07.421 Tabular[33046:207] (
)
2010-08-15 15:42:09.902 Tabular[33046:207] (
    (
            (
        Google,
        "https://www.google.com/"
    ),
            (
        "https://tabular.heroku.com/tab_stores/tester",
        "https://tabular.heroku.com/tab_stores/tester"
    ),
            (
        "test - Google Search",
        "http://www.google.com/search?client=safari&rls=en&q=test&ie=UTF-8&oe=UTF-8"
    ),
            (
        "Using POST method in XMLHTTPRequest(Ajax)",
        "http://www.openjs.com/articles/ajax_xmlhttp_using_post.php"
    ),
            (
        "json stringify - Google Search",
        "http://www.google.com/search?client=safari&rls=en&q=json stringify&ie=UTF-8&oe=UTF-8"
    ),
            (
        "json.stringify escape - Google Search",
        "http://www.google.com/search?q=json.stringify escape&hl=en&safe=off&client=safari&rls=en&ei=PUlaTNiYL4O78gbt8bXsAg&start=10&sa=N"
    )
),
    (
            (
        Google,
        "https://www.google.com/"
    )
)
)

1 Ответ

1 голос
/ 16 августа 2010
  • Похоже, что каждый элемент в cellData сам по себе является другим массивом. Это не строка NSString, поэтому назначение его «тексту» текстового поля вряд ли сработает (я удивлен, что он не падает). Если есть сомнения, позвоните [obj description], который должен вернуть строку NSString.
  • connection:didReceiveData: можно вызывать несколько раз для одного соединения. Ваш закомментированный код находится на правильном пути (буферизуйте все данные один раз и обработайте все в connectionDidFinishLoading:; альтернативно, обработайте его с помощью потокового API, если он у вас есть; я не думаю, что используемая вами библиотека JSON поддерживает что).
  • Вы любопытно делаете изменяемую копию данных, но затем не изменяете ее.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...