2013-02-05 4 views
0

아래 코드를 사용하여 데이터가있는 테이블 뷰를 채우기 위해 채우기를 사용하지만 테이블 뷰를 스크롤하면 응답이 중지되고 언젠가는 스크롤하여 짧은 거리. .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 

#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

귀하의 코드가 동기 요청의 전체 인하는 .m 파일입니다. 요청이 주 스레드에서 수행되기 때문에

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 그리기 등). 따라서 모든 데이터가 다운로드 될 때까지 처리되지 않습니다. 결과적으로 앱이 버그가 발생합니다.

저는 최근에 "iOS에서 동시 사용자 인터페이스 구현하기"라는 WWDC 2012 세션을 보았습니다. 아주 재미 있고 도움이됩니다. 기조 연설에서 삽화를 통해 물질을 쉽게 이해할 수 있습니다. 어쨌든, 그 주제에 대한 자원이 풍부합니다. "비동기 iOS"라는 구글에 가면 매우 유용한 자습서 등을 찾을 수 있습니다.

관련 문제