我在加载后更新UITableView对象时遇到问题。我有一种感觉,它与异步数据有关,但我不知所措。表代表和数据源被设置为UIView(CartViewController)。UITableView在LoadData调用后不显示数据
.H
@interface CartViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
NSDictionary *myCart;
NSArray *myCartItems;
UITableView *tableView;
}
@property (nonatomic, retain) IBOutlet UITableView *tableView;
@property (nonatomic, retain) NSDictionary *myCart;
@property (nonatomic, retain) NSArray *myCartItems;
- (IBAction)RemoveFromCart:(id)sender;
@end
.M
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)
#import "CartViewController.h"
#import "VariablesStore.h"
@implementation CartViewController
@synthesize myCart,myCartItems;
@synthesize tableView;
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[VariablesStore sharedInstance] CartURL]]];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (void)fetchedData:(NSData *)responseData
{
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary* cart = [json objectForKey:@"Cart"];
myCart = cart;
NSArray *itemList = [cart objectForKey:@"CartItemList"];
myCartItems = itemList;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [myCartItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel *skuNum = (UILabel *)[cell viewWithTag:1];
NSDictionary *cartItem = [myCartItems objectAtIndex:indexPath.row];
NSLog(@"Dictionary: %@", cartItem); // returns the cart item
NSLog(@"SkuFormatted: %@", [cartItem valueForKey:@"SKUFormatted"]); //shows the sku correctly
[skuNum setText:[cartItem valueForKey:@"SKUFormatted"]];
NSLog(@"skuNum:%@", skuNum.text); //shows (null) for the sku
return cell;
}
@end
我做几乎同样的事情在另一个视图,并进行比较,但我没有看到将导致该问题的任何差异。
我删除了第二个dispatch_async并没有任何东西。我甚至删除了第一个dispatch_async,刚刚在viewdidload上获得了数据,但仍然没有任何结果。数据以预期的结果返回(我可以在NSLog中看到它)。 – DJH 2012-02-05 16:58:45
尝试把'NSLog(@“返回的对象数量:%i”,[myCartItems count]);'返回之前,在' - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection'部分并检查日志是否存在是0以外的东西; – 2012-02-05 20:02:40
它被调用两次,一次在初始视图加载和一次当我调用表视图重新加载。第一次返回0,因为我没有加载数据。第二次返回预期金额(本例中为1)。 – DJH 2012-02-06 15:16:30