从服务器加载数据表视图会挂起它

时间:2013-02-05 09:44:29

标签: uitableview

我正在使用下面的代码用数据填充表视图,它也被填充但问题是在滚动表视图中它会挂起并且在一段时间之后它会滚动一小段距离。 .h文件是

#import <UIKit/UIKit.h>
#import "JSON.h"
@interface HomeViewController : UIViewController <UITabBarControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>

@property (strong, nonatomic) IBOutlet UINavigationBar *navigationBar;
@property (strong,nonatomic) IBOutlet UITableView *homeProfileTableview;
@property (nonatomic ,retain) UIImageView *clockImage;
@property (nonatomic,strong) UIImageView *ItemImage;
@property (nonatomic,strong) UIImageView *locationImage;
@property (nonatomic, retain) NSArray *Tableata;

@end

.m文件

#import "HomeViewController.h"
#import "CameraViewController.h"
#import "JSON.h"
#import "SBJsonParser.h"

@interface HomeViewController ()

@end

@implementation HomeViewController
@synthesize homeProfileTableview,clockImage,Tableata,ItemImage,locationImage;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tabBarController.delegate=self;
    [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"yellow_bar.png"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:1.0], UITextAttributeTextColor,[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowColor,[NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,[UIFont fontWithName:@"Georgia-BoldItalic" size:25.0], UITextAttributeFont,nil]];

    UIImage *image = [UIImage imageNamed:@"refresh.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
    [button addTarget:self action:@selector(refreshButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height)];
    [buttonView addSubview:button];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:buttonView];
    [self.navigationBar.topItem setRightBarButtonItem:backItem];


//    NSString *jsonString = [NSString
//                            stringWithContentsOfURL:[NSURL URLWithString:@"http://izisstechnology.com/garage/index.php?method=login&username=ashu&password=1234"]
//                            encoding:NSStringEncodingConversionAllowLossy
//                            error:nil];
    NSString *jsonString = [NSString
                            stringWithContentsOfURL:[NSURL URLWithString:@"http://izisstechnology.com/garage/index.php?method=home&start=0"]
                            encoding:NSStringEncodingConversionAllowLossy
                            error:nil];

    SBJsonParser *parser=[[SBJsonParser alloc]init];

    NSDictionary *results=[parser objectWithString:jsonString ];

    //NSDictionary *results = [parser objectWithString:jsonString error:nil];
    //[parser release], parser = nil;
    NSLog(@"%@",results);
    // Set tableData
    [self setTableata:[results objectForKey:@"new"]];
    [super viewDidLoad];

}
- (void)refreshButtonTapped {

}
- (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 the number of rows in the section.
    return [Tableata count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"homeProfileTableIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }
    NSDictionary *item = [Tableata objectAtIndex:[indexPath row]];
    NSURL *url = [NSURL URLWithString:[item objectForKey:@"seller_image"]];


    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc] initWithData:data];


    //clock image
    CGRect imageFrame = CGRectMake(240,10, 20, 20);
    self.clockImage = [[UIImageView alloc] initWithFrame:imageFrame];    
    self.clockImage.image = [UIImage imageNamed:@"clock.jpg"];    
    [cell.contentView addSubview:self.clockImage];


    //location image
    CGRect imageFrame1 = CGRectMake(80,20, 20, 20);
    self.locationImage = [[UIImageView alloc] initWithFrame:imageFrame1];
    self.locationImage.image = [UIImage imageNamed:@"location.jpg"];
    [cell.contentView addSubview:self.locationImage];


    //username
    UILabel *username=[[UILabel alloc] initWithFrame:CGRectMake(80,0, 70, 20)];
    username.text=[item objectForKey:@"seller_name"];
    UIFont *myFont = [ UIFont fontWithName: @"futura" size: 18.0 ];
    username.font  = myFont;
    [cell.contentView addSubview:username];

    //user location
    UILabel *userlocation=[[UILabel alloc] initWithFrame:CGRectMake(100,20, 70, 20)];
    userlocation.text=[item objectForKey:@"prod_country"];
    UIFont *myFont2 = [ UIFont fontWithName: @"futura" size: 18.0 ];
    userlocation.font  = myFont2;
    [cell.contentView addSubview:userlocation];

    //item image
    NSURL *url1 = [NSURL URLWithString:[item objectForKey:@"item_image1"]];


    NSData *data1 = [[NSData alloc] initWithContentsOfURL:url1];
    UIImage *image1 = [[UIImage alloc] initWithData:data1];
    CGRect imageFrame2 = CGRectMake(20,40, 280, 320);
    self.ItemImage = [[UIImageView alloc] initWithFrame:imageFrame2] ;

    self.ItemImage.image = image1;

    [cell.contentView addSubview:self.ItemImage];



    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    playButton.frame = CGRectMake(20, 5, 30, 30);
    [playButton setTitle:@"" forState:UIControlStateNormal];
    playButton.backgroundColor = [UIColor clearColor];
    [playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
    UIImage *buttonImageNormal = image;
    UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [playButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
    [cell.contentView addSubview:playButton];
    return cell;


}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 380;
}
- (void)viewDidUnload {
    [self setNavigationBar:nil];
    [super viewDidUnload];
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[CameraViewController class]]) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                      initWithTitle:@"Choose Source Type?"
                                      delegate:self
                                      cancelButtonTitle:@"Cancel"
                                      destructiveButtonTitle:nil
                                      otherButtonTitles:@"Select From Library", @"Capture From Camera", nil];
        [actionSheet showFromTabBar:tabBarController.tabBar];
        return NO;
    }
    return YES;
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            CameraViewController *cameraViewController=[self.tabBarController.viewControllers objectAtIndex:2];
            if (!cameraViewController.imagePicker) {
                cameraViewController.imagePicker =[[UIImagePickerController alloc] init];
                cameraViewController.imagePicker.allowsEditing = YES;
            }
            cameraViewController.imagePicker.delegate=self;
            cameraViewController.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:cameraViewController.imagePicker
                               animated:YES completion:nil];
        }
            break;
        case 1:
        {
            CameraViewController *cameraViewController=[self.tabBarController.viewControllers objectAtIndex:2];
            if (!cameraViewController.imagePicker) {
                cameraViewController.imagePicker =[[UIImagePickerController alloc] init];
                cameraViewController.imagePicker.allowsEditing = YES;
            }
            if ([UIImagePickerController isSourceTypeAvailable:
                 UIImagePickerControllerSourceTypeCamera])
            {
                cameraViewController.imagePicker.delegate=self;
                cameraViewController.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:cameraViewController.imagePicker
                                   animated:YES completion:nil];
            }
        }
            break;
        case 2:
            [self dismissViewControllerAnimated:YES completion:nil];
            break;
        default:
            break;
    }
}
-(void)imagePickerController:
(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    CameraViewController *cameraViewController=[self.tabBarController.viewControllers objectAtIndex:2];
    cameraViewController.imageSelected=nil;
    UIImage *image = info[UIImagePickerControllerEditedImage];
    cameraViewController.imageSelected=image;
    cameraViewController.imagePicker.delegate=cameraViewController;
    [self dismissViewControllerAnimated:YES completion:nil];
    self.tabBarController.selectedViewController=cameraViewController;
}

-(void)imagePickerControllerDidCancel:
(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end

1 个答案:

答案 0 :(得分:1)

您的代码充满了同步请求。例如:

 NSString *jsonString = [NSString
                            stringWithContentsOfURL:[NSURL URLWithString:@"http://izisstechnology.com/garage/index.php?method=home&start=0"]
                            encoding:NSStringEncodingConversionAllowLossy
                            error:nil];

NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc] initWithData:data];

当您执行同步请求时,整个UI会被阻止,因为请求是在主线程上执行的。基本上UIKit的大部分内容都是在主线程上完成的,例如处理触摸,绘制UI等。例如,触摸所有数据后才会被处理。因此,您的应用程序会出错。

我最近观看了WWDC 2012的一个名为“在iOS上构建并发用户界面”的会话。这很有趣,也很有帮助。主题演讲中的插图使得理解材料变得容易。无论如何,有关该主题的大量资源,你只需要谷歌“异步iOS”,你会发现非常有用的教程等。