在ViewController iOS之前加载DataController

时间:2013-03-31 16:48:07

标签: ios objective-c

我有2个控制器,1个是从JSON加载数据,另一个是简单的UITableViewController。我的问题是视图在数据之前加载。如何在表格之前加载数据?我是Objective-C OOP的新手:/

代码

#import "MasterViewController.h"

#import "DetailViewController.h"

#import "DealsDataController.h"

#import "Deals.h"


@implementation MasterViewController

- (void)awakeFromNib
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        self.clearsSelectionOnViewWillAppear = NO;
        self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
    }
    [super awakeFromNib];

    self.dataController = [[DealsDataController alloc] init];
    NSLog(@"this is the awake from nib count %i",[self.dataController countOfList]);

}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

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

#pragma mark - Table View

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"did this count the list %i",[self.dataController countOfList]);
    return [self.dataController countOfList];

}

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

    static NSString *CellIdentifier = @"DealCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    Deals *dealAtIndex = [self.dataController objectInListAtIndex:indexPath.row];
    [[cell textLabel] setText:dealAtIndex.name];

    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return NO;
}


/*
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_objects removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        NSDate *object = _objects[indexPath.row];
        self.detailViewController.detailItem = object;
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        NSDate *object = _objects[indexPath.row];
        [[segue destinationViewController] setDetailItem:object];
    }
}

 */
@end

和数据控制器

#import "DealsDataController.h"
#import "Deals.h"

@implementation DealsDataController
@synthesize masterDealsList = _masterDealsList;

-(id)init {
    if (self = [super init]) {
        [self initializeDataList];
        return self;
    }
    return nil;
}

-(NSMutableArray *)masterDealsList {
    if (!_masterDealsList) {
        _masterDealsList = [[NSMutableArray alloc] init];
    }
    return _masterDealsList;
}

-(void)setMasterDealsList:(NSMutableArray *)newList {
    if (_masterDealsList != newList) {
        _masterDealsList = newList;
    }
}

- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary *json = [NSJSONSerialization
                          JSONObjectWithData:responseData //1
                          options:kNilOptions
                          error:&error];

    _deals = [json objectForKey:@"deals"]; //2

    NSLog(@"deals: %@", _deals);
    NSArray *dealName = [_deals valueForKey:@"deal_name"];
    NSLog(@"deals Name: %@", dealName);

    for (int i = 1;i <= [_deals count]; i++) {
    NSDictionary* dict = [_deals objectAtIndex:i-1];
    Deals *deal =[[Deals alloc] initWithProdID:1 name:[dict valueForKey:@"deal_name"] description:[dict objectForKey:@"deal_description"] price:10.00 specs:@"specs" terms:@"terms"];
    [self addDealWithDeal:deal];

    NSLog (@"masterListCount %i ", [self countOfList]);

    }

}

-(void)initializeDataList {
    //NSDate *today = [NSDate date];
    dispatch_async(sweetDealsQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:sweetDealsURL];
        [self performSelectorOnMainThread:@selector(fetchedData:)
                               withObject:data waitUntilDone:YES];
    });

}

-(NSUInteger)countOfList {

    return [self.masterDealsList count];

}

-(Deals *)objectInListAtIndex:(NSUInteger)theIndex {

    return [self.masterDealsList objectAtIndex:theIndex];
}

-(void)addDealWithDeal:(Deals *)deal {

      [self.masterDealsList addObject:deal];
}


@end

3 个答案:

答案 0 :(得分:2)

在MVC中,每个视图通常只有一个视图控制器。因此,单个视图控制器将负责一个视图上的所有显示。当然,您可以使用辅助类,或使用子视图控制器(例如小部件),或者如果您正在为iPad开发,则可能有两个视图控制器(一个用于侧面菜单,一个用于主视图)。

我建议您执行以下操作

  1. 使您的DataController成为NSObject的子类,而不是UIViewController。据我所知,它是一个数据访问类,不负责UI。
  2. 在MasterViewController的viewDidLoad方法中,分配并初始化DataController对象并触发其数据加载方法。
  3. 设置回调,以便在获取数据时,使用数据调用 MasterViewController 上的方法。或者将MasterViewController设置为DataController的委托,完成后,将数据分配给MasterViewController的属性。

答案 1 :(得分:0)

我猜你需要在初始化TableViewController之前执行数据加载,并在获得响应时加载TableViewController。对于那个refer this post如何等待某个方法完成执行,在该方法中执行数据加载。

答案 2 :(得分:0)

可以在加载数据时显示带有活动指示符覆盖的空白表格视图。数据加载完成后,您只需使用数据重新加载tableview并删除活动指示符。 [tableview reloaddata]将调用所有数据源委托方法,然后将数据包含在其中。