ios - 在 ViewController iOS 之前加载 DataController

标签 ios objective-c

我有 2 个 Controller ,1 个是从 JSON 加载数据,另一个是一个简单的 UITableViewController。我的问题是 View 是在数据之前加载的。如何在我的表之前加载数据?我是 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

最佳答案

在 MVC 中,通常每个 View 都有一个 View Controller 。因此,单个 View Controller 将负责在一个 View 上显示的所有内容。当然,您可以使用辅助类,或使用 subview Controller (例如小部件),或者如果您正在为 iPad 开发,您可能有两个 View Controller (一个用于侧边菜单,一个用于主视图)。

我建议你做以下事情

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

关于ios - 在 ViewController iOS 之前加载 DataController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731871/

相关文章:

iphone - 屏蔽的 UIView 上的 UIGestureRecogniser?

iOS导航栏总是空的

objective-c - 重新初始化对象

objective-c - 将 NSData Objective-C 代码转换为 Swift 时遇到问题

iphone - 防止 UIDatePicker 与 TableView 一起滚动

ios - 插入 Collection View 单元格后是否可以重复使用?

ios - 在 umbrella header 中包含 -Swift.h

ios - 从文件中读取 JSON 数据 Swift 2.0 适用于模拟器但不适用于设备,返回 json null

HTML 页面无法在纵向 iPhone/iPad 上调整大小

ios - NS_Deprecated 等效于 3rd 方框架