2015-01-14 2 views
0

Итак, у меня есть UITableView и запрос Parse, и запрос может извлекать объекты из синтаксического анализа. Но TableView не показывает их.UITableView with Parse Query Not Loading

Вот мой код, я объясню более ниже:

- (PFQuery *)query { 
    NSLog(@"hello"); 
    PFQuery *query = [PFQuery queryWithClassName:@"Posts"]; 

    // If no objects are loaded in memory, we look to the cache first to fill the table 
    // and then subsequently do a query against the network. 


    // Query for posts near our current location. 

    // Get our current location: 
    //CLLocation *currentLocation = [self.dataSource currentLocationForWallPostsTableViewController:self]; 
    CLLocationAccuracy filterDistance = [[NSUserDefaults standardUserDefaults] doubleForKey:PAWUserDefaultsFilterDistanceKey]; 

    // And set the query to look by location 
    PFGeoPoint *point = [PFGeoPoint geoPointWithLatitude:40.941984 
               longitude:-72.88712399999997]; 
    [query whereKey:PAWParsePostLocationKey nearGeoPoint:point withinKilometers:PAWMetersToKilometers(filterDistance)]; 
    [query includeKey:PAWParsePostUserKey]; 

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
     if (!error) { 
      // The find succeeded. 
      NSLog(@"Successfully retrieved %lu users.", (unsigned long)objects.count); 
      self.myArray = objects; 
     } else { 
      // Log details of the failure 
      NSLog(@"Error: %@ %@", error, [error userInfo]); 
     } 
    }]; 


    NSLog(@"work"); 

    return query; 
} 

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



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return self.myArray.count; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object { 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 
    NSLog(@"yy"); 
    NSString *kk= [object objectForKey:@"text"]; 
    NSLog(@"%@",kk); 
    // Configure the cell 
    cell.textLabel.text = [object objectForKey:@"text"]; 

    return cell; 
} 

Две вещи, которые я нашел, что может быть причиной проблемы является:

  1. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section вызывается перед запросом, что для меня не имеет смысла.

  2. И поскольку он вызывается перед запросом, array.count равен 0;

Поэтому я не понимаю, почему эта строка будет вызываться перед запросом. Если у Вас есть предложения, пожалуйста, дайте мне знать!

Обновление Это называется три раза, а второй nslog не вызывается.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     NSLog(@"Fsa"); 
     return self.myArray.count; 
     NSLog(@"Successfully retrieved %lu .", (unsigned long)self.myArray.count); 

    } 

В моей .h

UIViewController <UITableViewDataSource, UITableViewDelegate> 
@property (weak, nonatomic) IBOutlet UITableView *tableView; 

enter image description here

+0

Что вы имеете против ParseQueryTableViewController? – soulshined

+0

@soulshined Ничего не хаха. Я использовал его, но остановился, потому что он не позволял настройки, которые я хотел. – Jack

+0

И ваш вызов этого запроса в viewDidLoad? – soulshined

ответ

3

Этого метод:

- (PFQuery *)queryForTable 

возвращает запрос, автоматически заполняющий PFObject в cellForRowAtIndexPath:object: в категории

- (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object { 

Что вы сделали, однако, выполните query в вашем методе queryForTable. (1) Вам не нужно выполнять запрос, вам просто нужно его вернуть, но (2) кажется, что вы строго выполняете этот запрос, чтобы заполнить self.myArray, который затем используется для использования в качестве возвращаемого значения в numberOfRowsInSection:.Проблема с # 2 заключается в том, что запрос, который вы выполняете в queryForTable, выполняется асинхронно, поэтому self.myArray все еще может быть пустым к тому времени, когда вызывается numberOfRowsInSection:. Так вот что происходит - self.myArray.count = 0, и поэтому cellForRowAtIndexPath: не будет вызываться.

Но самая большая проблема из всех, # 3 заключается в том, что - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object может использоваться только в PFQueryTableViewController, поэтому вам придется использовать запрос и стандартные методы делегата UITableView.

Попробуйте вместо этого:

- (void)viewDidLoad { 

    NSLog(@"hello"); 
    PFQuery *query = [PFQuery queryWithClassName:@"Posts"]; 

    // Query for posts near our current location. 

    // Get our current location: 
    //CLLocation *currentLocation = [self.dataSource currentLocationForWallPostsTableViewController:self]; 
    CLLocationAccuracy filterDistance = [[NSUserDefaults standardUserDefaults] doubleForKey:PAWUserDefaultsFilterDistanceKey]; 

    // And set the query to look by location 
    PFGeoPoint *point = [PFGeoPoint geoPointWithLatitude:40.941984 
               longitude:-72.88712399999997]; 
    [query whereKey:PAWParsePostLocationKey nearGeoPoint:point withinKilometers:PAWMetersToKilometers(filterDistance)]; 
    [query includeKey:PAWParsePostUserKey]; 

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
     if (!error) { 
      // The find succeeded. 
      NSLog(@"Successfully retrieved %lu users.", (unsigned long)objects.count); 
      self.myArray = objects; 

      dispatch_async(dispatch_get_main_queue(), ^{ 
       [self.tableView reloadData]; 
      }); 

     } else { 
      // Log details of the failure 
      NSLog(@"Error: %@ %@", error, [error userInfo]); 
     } 
    }]; 
} 

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return self.myArray.count; 
} 

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 
    NSLog(@"yy"); 
    NSString *kk= [[self.myArray objectAtIndex:indexPath.row] objectForKey:@"text"]; 
    NSLog(@"%@",kk); 
    // Configure the cell 
    cell.textLabel.text = [[self.myArray objectAtIndex:indexPath.row] objectForKey:@"text"]; 

    return cell; 
} 
+0

Нужно ли мне tableView: numberOfRowsInSection? Я использую tableView в регулярном viewcontroller. – Jack

+0

@Jack В использовании метода запросов (PFQuery *) вы фактически использовали вместо метода queryForTable - (PFQuery *) queryForTable? –

+0

Да, я изменил это. – Jack

0

Попробуйте явного вызова его в viewDidLoad. Если self.myArray = объекты не возвращают нуль, этого должно быть достаточно. Это заставит его загрузить в обход других способов загрузки первого:

-(void)viewDidLoad { 
    ... 
    [self locationQuery]; 
} 

-(PFQuery *)locationQuery { 

    CLLocationAccuracy filterDistance = [[NSUserDefaults standardUserDefaults] doubleForKey:PAWUserDefaultsFilterDistanceKey]; 
    PFGeoPoint *point = [PFGeoPoint geoPointWithLatitude:40.941984 
              longitude:-72.88712399999997]; 

    PFQuery *query = [PFQuery queryWithClassName:@"Posts"]; 
    [query whereKey:PAWParsePostLocationKey nearGeoPoint:point withinKilometers:PAWMetersToKilometers(filterDistance)]; 
    [query includeKey:PAWParsePostUserKey]; 
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
      if (!error) { 
       // The find succeeded. 
       NSLog(@"Successfully retrieved %lu users.", (unsigned long)objects.count); 
       self.myArray = objects; 
       //OR : 
       self.myArray = [objects valueForKey:@"NameOfParse.comClassColumnHere"]; 
       [self.tableView reloadData]; 
      } else { 
       // Log details of the failure 
       NSLog(@"Error: %@ %@", error, [error userInfo]); 
      } 
    }]; 
     return query; 
} 

Кроме того, ваш cell.textLabel.text ссылается то, что не существует ..

NSString * кк = [объект objectForKey :@"текст"]; NSLog (@ "% @", kk); // Конфигурирование ячейки cell.textLabel.text = [object objectForKey: @ "text"];

Что это? если вы хотите, чтобы массив вы опрошены вы должны сделать:

cell.textLabel.text = [NSString stringWithFormat:@"%@", [self.myArray objectAtIndex:indexPath.row]]; 
+0

У меня уже было [self loadQuery]; в моем представленииDidLoad. – Jack

+0

@Jack Я спросил об этом. Если вы имеете в виду, что у вас есть другой запрос, просто назовите метод что-то еще, это не имеет значения. – soulshined

+0

да, имена разные, но у меня уже есть что-то в моем представленииDidLoad, вызывающее запрос. – Jack

1

Попробуйте это:

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (!error) { 
     // The find succeeded. 
     NSLog(@"Successfully retrieved %lu users.", (unsigned long)objects.count); 
     self.myArray = objects; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self.tableView reloadData]; 
     }); 

    } else { 
     // Log details of the failure 
     NSLog(@"Error: %@ %@", error, [error userInfo]); 
    } 
}]; 
+0

Я просто попробовал это, и я это разбил, сказав: «UITableView dataSource должен вернуть ячейку из tableView: cellForRowAtIndexPath:« Но у меня есть связанный источник данных и делегатов. – Jack

+0

Я уверен, что это правильное решение проблемы в вашем вопросе: 'UITableView' теперь пытается отобразить данные. Вы должны убедиться, что '-tableView: cellForRowAtIndexPath:' возвращает действительную ячейку, но это другая проблема. Я сомневаюсь в вызове метода '-tableView: cellForRowAtIndexPath: object:'. –

+0

@ ThomasMüller Это неправильный ответ, к сожалению, и tableView: cellForRowAtIndexPath: не вызывается, потому что numberOfRowsInSection возвращает 0 ... Я постараюсь написать ответ, потому что я думаю, что этот вопрос быстро сходит с кроличьей дыры. .. –