2014-09-19 50 views
0

對於我的MatchCenterViewController,我設置了在2秒鐘的時間間隔後運行MatchCenter函數viewDidAppear。此功能用文字和圖像填充UITableView。問題是,當用戶試圖滾動瀏覽UITableView或從MatchCenterViewController出現時點擊任何單元格,直到MatchCenter函數完成加載,該應用程序崩潰。如何在用戶點擊或滾動UITableView時取消某個功能?

它似乎正在發生,因爲如果用戶在單元格上滾動或點擊以打開模型'WebViewSegue',它將與試圖填充/更新表的MatchCenter函數衝突。我想要發生的是,如果用戶開始滾動瀏覽表格或點擊單元格,則退出viewDidAppear中的MatchCenter函數。

我該如何形成這種語法,並且一旦我這樣做,我是否必須將它放在'didSelectRowAtIndexPath'和一個單獨的函數中,以考慮滾動?

MatchCenterViewController.m:

#import "MatchCenterViewController.h" 
#import <UIKit/UIKit.h> 

@interface MatchCenterViewController() <UITableViewDataSource, UITableViewDelegate> 
@property (nonatomic, strong) UITableView *matchCenter; 
@end 

@implementation MatchCenterViewController 


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
    } 
    return self; 
} 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle]; 
    self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100); 
    _matchCenter.dataSource = self; 
    _matchCenter.delegate = self; 
    [self.view addSubview:self.matchCenter]; 

    _matchCenterArray = [[NSArray alloc] init]; 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    self.matchCenterArray = [[NSArray alloc] init]; 

    // Delay to allow MatchCenter item enough time to be added before pinging ebay 
    [NSThread sleepForTimeInterval:2]; 

    [PFCloud callFunctionInBackground:@"MatchCenter" 
         withParameters:@{} 
           block:^(NSArray *result, NSError *error) { 

            if (!error) { 
             _matchCenterArray = result; 
             [_matchCenter reloadData]; 

             NSLog(@"Result: '%@'", result); 
            } 
           }]; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return _matchCenterArray.count; 
} 

//the part where i setup sections and the deleting of said sections 

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { 
    return 21.0f; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section 
{ 
    return 0.01f; 
} 


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)]; 
    headerView.backgroundColor = [UIColor lightGrayColor]; 

    _searchTerm = [[[[_matchCenterArray objectAtIndex:section] objectForKey:@"Top 3"] objectAtIndex:3]objectForKey:@"Search Term"]; 

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)]; 
    headerLabel.text = [NSString stringWithFormat:@"%@", _searchTerm]; 
    headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]; 
    headerLabel.textColor = [UIColor whiteColor]; 
    headerLabel.backgroundColor = [UIColor lightGrayColor]; 
    [headerView addSubview:headerLabel]; 


    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    deleteButton.tag = section; 
    deleteButton.frame = CGRectMake(300, 2, 17, 17); 
    [deleteButton setImage:[UIImage imageNamed:@"xbutton.png"] forState:UIControlStateNormal]; 
    [deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    [headerView addSubview:deleteButton]; 
    return headerView; 

} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 3; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Initialize cell 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (!cell) { 
     // if no cell could be dequeued create a new one 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    // No cell seperators = clean design 
    tableView.separatorColor = [UIColor clearColor]; 

    // title of the item 
    cell.textLabel.text = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Title"]; 
    cell.textLabel.font = [UIFont boldSystemFontOfSize:14]; 

    // price of the item 
    cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@", _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Price"]]; 
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f]; 

    // image of the item 
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Image URL"]]]; 
    [[cell imageView] setImage:[UIImage imageWithData:imageData]]; 

    return cell; 

} 


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return 65; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    self.itemURL = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Item URL"]; 
    [self performSegueWithIdentifier:@"WebViewSegue" sender:self]; 
} 

- (void)deleteButtonPressed:(id)sender 
{ 
    // links button 
    UIButton *deleteButton = (UIButton *)sender; 

    // Define the sections title 
    NSString *sectionName = _searchTerm = [[[[_matchCenterArray objectAtIndex:deleteButton.tag] objectForKey:@"Top 3"] objectAtIndex:3]objectForKey:@"Search Term"]; 

    // Run delete function with respective section header as parameter 
    [PFCloud callFunctionInBackground:@"deleteFromMatchCenter" 
         withParameters: 
         @{@"searchTerm": sectionName,} 
           block:^(NSDictionary *result, NSError *error) { 
            if (!error) { 
             [PFCloud callFunctionInBackground:@"MatchCenter" 
                  withParameters:@{ 
                      @"test": @"Hi", 
                      } 
                    block:^(NSArray *result, NSError *error) { 

                     if (!error) { 
                      _matchCenterArray = result; 
                      [_matchCenter reloadData]; 

                      NSLog(@"Result: '%@'", result); 
                     } 
                    }]; 

            } 
           }]; 
} 



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



#pragma mark - Navigation 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    WebViewController *controller = (WebViewController *) segue.destinationViewController; 
    controller.itemURL = self.itemURL; 
} 


@end 
+0

以及我不會睡覺主線程2秒鐘任何occassion,如果你還想要一些圖像加載到你的表,儘量不要把同步請求 - 這實在是太慢了,如果你不沒有快速上網的完美設備,而是尋找GCD解決方案。並btw - >如果你想重新加載表或做任何其他應該在主線程運行,除了我之前提到的東西 – deathhorse 2014-09-19 20:06:45

+0

,你最大的問題是,你在委託方法告訴你,你已經有3個電池。同時你的matcharray仍然是空的,當你點擊3個單元格中的任何一個時,你會調用didSelectRow:atIndexPath:delegate method - >這肯定會崩潰,因爲你試圖在不存在的索引處獲取對象在你的空陣列中。 – deathhorse 2014-09-19 20:10:33

回答

1

你堵在主線程上!不好!看到這個問題:NSThread sleepfortimeinterval blocks main thread

有一個更好的延遲方法是使用GCD。試試這個:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
    [PFCloud callFunctionInBackground:@"MatchCenter" 
         withParameters:@{} 
           block:^(NSArray *result, NSError *error) { 
            if (!error) { 
             // Might not be necessary, but it would be good to check to make 
             // sure _matchCenterArray and _matchCenter still exist. 
             if (_matchCenterArray && _matchCenter) { 
              // I am not sure if this block is invoked on the main thread 
              dispatch_async(dispatch_get_main_queue(), ^{ 
               _matchCenterArray = result; 
               [_matchCenter reloadData]; 

               NSLog(@"Result: '%@'", result); 
              }) 
             } 
            } 
           }]; 
}); 
+0

啊,有道理,謝謝你的提示。任何想法如何在我的主要問題中解決問題? – Ghobs 2014-09-19 20:04:43

+0

當然!只需在你的viewController中添加一個BOOL(如果你願意的話,可以將它作爲一個屬性),並且當該塊被禁用時將其設置爲YES。然後在PFCloud塊的開頭添加一條if語句並檢查BOOL的值。如果是YES,則返回。 – 2014-09-19 20:13:30

+0

哎呀。我使用bool來告訴'didSelectRowAtIndexPath'中的代碼只在bool == YES時運行,當'MatchCenter'完成時它被設置爲yes。當MatchCenter仍在運行時點擊一行不會導致崩潰,但滾動仍然會發生。如果我開始滾動,你認爲你可以告訴我使用這個bool方法來讓函數返回的語法嗎?我對Obj-C有點新鮮:) – Ghobs 2014-09-19 22:11:11

相關問題