2011-09-20 70 views
0

我的程序工作正常,但問題是我想用目前的行擴展我的行。 我有API,每頁給我10條新聞,我想用此新聞標題升級我的tableViewRows。在開始的時候,我解析了第一頁的Api(IDValue用於頁面),首先我的表視圖在UIAlert之後加載,並在完成解析後開始解析([myTableView reloadData];)更新tableView,有一個第11行有「加載更多10新聞選項」,當我再次點擊這個解析開始,但最終我想用我的表格視圖來擴展下一個10條新聞,比如(前10 +新10)news = 20新聞(行)在TableView中,但它給我「SIGABRT」錯誤。問題在擴展tableView行與重新加載10-10新聞

我與你分享我的.h和.m文件通過這個,並給我的建議plz我怎麼能來這個錯誤。

錯誤是:

2011-09-20 14:28:57.278的工作[8692:207] *終止應用程序由於 未捕獲的異常 'NSRangeException',原因:「 - [NSMutableArray裏 objectAtIndex:]:索引11超出範圍[0..9]」 * *在第一擲調用堆棧:(0的CoreFoundation
0x013ac5a9 exceptionPreprocess + 185 1 libobjc.A。dylib
0x01500313 objc_exception_throw + 44 2的CoreFoundation
0x013a20a5 - [__ NSArrayM objectAtIndex:] + 261 3 FashionUnited
0x00005288 - [NewsMainVC的tableView:的cellForRowAtIndexPath:] + 648 4
的UIKit 0x00673b98 - [UITableView的(UITableViewInternal) _createPreparedCellForGlobalRow: withIndexPath:] + 634 5的UIKit
0x006694cc - [UITableView的(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75 6的UIKit
0x0067e8cc - [UITableView的(_UITableViewPrivate)_updateVisibleCellsNow:] + 1561 7的UIKit 0x0067690 Ç - [UITableView的layoutSubviews] + 242 8 QuartzCore
0x01e06a5a - [CALayer的layoutSublayers] + 181 9 QuartzCore
0x01e08ddc CALayerLayoutIfNeeded + 220 10 QuartzCore
0x01dae0b4 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310 11 QuartzCore 0x01daf294 _ZN2CA11Transaction6commitEv + 292 12 QuartzCore
0x01daf46d _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99 13的CoreFoundation 0x0138d89b __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION
+ 27 14 CoreFoun dation 0x013226e7 __CFRunLoopDoObservers + 295 15的CoreFoundation 0x012ea857 CFRunLoopRunSpecific + 231 16的CoreFoundation
0x012ea761 CFRunLoopRunInMode + 97個17 GraphicsServices
0x019f61c4 GSEventRunModal + 217個18 GraphicsServices
0x019f6289 GSEventRun + 115 19的UIKit
0x0060cc93 UIApplicationMain + 1160 20 FashionUnited
0x00002d49 main + 121 21 FashionUnited
0x00002cc5 start + 53)拋出 的實例後終止'NSException'

並且每次用+10新聞擴展TableRows。

.h文件中

NewsMainVC.h

@class DetailNewsDisplayController,NewsInfo,NewsParser; 

@interface NewsMainVC : UIViewController <UITableViewDelegate,UITableViewDataSource> { 

    int selectedLanguage; 
    int currentLanguage; 

    NSInteger IDValue; 

    NSMutableData *responseData; 

    NewsParser *parser; 

    NSURL *url; 
    UIAlertView *alert; 
    NewsInfo *aNewsInfo; 

    NSString *FinalString; 
    UIAlertView *alertNext; 

    UITableViewCell *nibLoadedCell; 
    UIActivityIndicatorView *spinnerNext; 

    DetailNewsDisplayController *ndvController; 

    UIActivityIndicatorView *spinner; 
    UIAlertView *alertt; 

    IBOutlet UILabel *textLabel; 
    IBOutlet UITextView *textView; 
    IBOutlet UILabel *titleLabel; 
    IBOutlet UIImageView *imageLabel; 
    IBOutlet UITableView *myTableView; 


} 
@property (nonatomic, retain) UIAlertView *alertt; 
@property (nonatomic, retain) UIActivityIndicatorView *spinner; 
@property (assign, readwrite) NSInteger IDValue; 
@property (assign,readwrite) int selectedLanguage; 
@property (nonatomic, retain) NSString *FinalString; 
@property (nonatomic, retain) IBOutlet UILabel *pages; 
@property (nonatomic,retain) IBOutlet UITableViewCell *nibLoadedCell; 
@property (nonatomic,retain) NSData *responseData; 

-(IBAction) goToOptions:(id)sender; 

- (void) parseXML; 

-(NSString*) languageSelectedStringForKey:(NSString*) key; 

.m文件

@implementation NewsMainVC 
@synthesize selectedLanguage; 
@synthesize nibLoadedCell,optionPageVC,FinalString,IDValue,spinner,alertt,responseData; 


extern int global; 


- (void)viewDidLoad 
{ 
    // Do any additional setup after loading the view from its nib. 

    appDelegate = (WorkAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    IDValue = 1; 
    textLabel.text=[self languageSelectedStringForKey:@"Welcome to Advance Localization"]; 

    NSString *mainWaitMessage = NSLocalizedString (@"Contacting Server\nPlease Wait...", @"Contacting Server\nPlease Wait..."); 
    alert = [[[UIAlertView alloc] initWithTitle:mainWaitMessage message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease]; 
    [alert show]; 
    spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; 
    spinner.center = CGPointMake(alert.bounds.size.width/2, alert.bounds.size.height - 50); 
    [alert addSubview:spinner]; 
    [spinner startAnimating]; 

    [super viewDidLoad]; 

} 

- (void)viewWillAppear:(BOOL)animated{ 

    [myTableView reloadData]; 
} 


#pragma ---------------------- 
#pragma Select APi According to selectedLanguage 

-(NSString*) languageSelectedStringForKey:(NSString*) key 
{ 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"zh" ofType:@"lproj"]; 

    if(selectedLanguage==MGD_LANG) 
    { 

     FinalString = [[NSString alloc] initWithFormat:@"http://www.xyz.com/api.php?page_id=%d",IDValue]; 

    } 
    else if(selectedLanguage==TKY_LANG) 
    { 

     FinalString = [[NSString alloc] initWithFormat:@"http://www.abc.com/api.php?page_id=%d",IDValue]; 

    } 

    url = [[NSURL alloc] initWithString:FinalString]; 
    [FinalString release]; 

    // Create the Request. 
    NSURLRequest *request = [NSURLRequest requestWithURL:url 
              cachePolicy:NSURLRequestUseProtocolCachePolicy 
             timeoutInterval: 30.0]; 
    // [url release]; 

    // Create the connection and send the request 
    NSURLConnection *connection = 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    // Make sure that the connection is good 
    if (connection) { 
     // Instantiate the responseData data structure to store to response 
     self.responseData = [NSMutableData data]; 

    } 
    else { 
     NSLog (@"The connection failed"); 
    } 

    NSBundle* languageBundle = [NSBundle bundleWithPath:path]; 
    NSString* str=[languageBundle localizedStringForKey:key value:@"" table:nil]; 

    return str; 

} 

#pragma mark - 
#pragma mark NSURLConnection delegate methods 

// Called when a redirect will cause the URL of the request to change 
- (NSURLRequest *)connection:(NSURLConnection *)connection 
      willSendRequest:(NSURLRequest *)request 
      redirectResponse:(NSURLResponse *)redirectResponse 
{ 
    NSLog (@"connection:willSendRequest:redirectResponse:"); 
    return request; 
} 

// Called when the server requires authentication 
- (void)connection:(NSURLConnection *)connection 
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    NSLog (@"connection:didReceiveAuthenticationChallenge:"); 
} 

// Called when the authentication challenge is cancelled on the connection 
- (void)connection:(NSURLConnection *)connection 
didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    NSLog (@"connection:didCancelAuthenticationChallenge:"); 
} 

// Called when the connection has enough data to create an NSURLResponse 
- (void)connection:(NSURLConnection *)connection 
didReceiveResponse:(NSURLResponse *)response { 
    NSLog (@"connection:didReceiveResponse:"); 
    NSLog(@"expectedContentLength: %qi", [response expectedContentLength]); 
    NSLog(@"textEncodingName: %@", [response textEncodingName]); 

    [self.responseData setLength:0]; 

} 

// Called each time the connection receives a chunk of data 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSLog (@"connection:didReceiveData:"); 

    // Append the received data to our responseData property 
    [self.responseData appendData:data]; 

} 

// Called before the response is cached 
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection 
        willCacheResponse:(NSCachedURLResponse *)cachedResponse 
{ 
    NSLog (@"connection:willCacheResponse:"); 
    // Simply return the response to cache 
    return cachedResponse; 
} 

// Called when the connection has successfully received the complete response 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog (@"connectionDidFinishLoading:"); 

    // Convert the data to a string and log the response string 
    NSString *responseString = [[NSString alloc] 
           initWithData:self.responseData 
           encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response String: \n%@", responseString); 

    [responseString release]; 
    [connection release]; 

    [self parseXML]; 


} 

// Called when an error occurs in loading the response 
- (void)connection:(NSURLConnection *)connection 
    didFailWithError:(NSError *)error 
{ 
    NSLog (@"connection:didFailWithError:"); 
    NSLog (@"%@",[error localizedDescription]); 

    [connection release]; 

} 


- (void) parseXML{ 

    NSLog (@"parseXML"); 

    // Initialize the parser with our NSData from the RSS feed 
    NSXMLParser *xmlParser = [[NSXMLParser alloc] 
           initWithData:self.responseData]; 

    //Initialize the delegate. 
    parser = [[NewsParser alloc] initXMLParser]; 

    //Set delegate 
    [xmlParser setDelegate:parser]; 

    // Start the parser 
    if (![xmlParser parse]) 
    { 
     NSLog (@"An error occurred in the parsing");  
    } 

    [myTableView reloadData]; 

    if (IDValue == 1) { 
    [spinner stopAnimating]; 
    [alert dismissWithClickedButtonIndex:0 animated:YES]; 
    } 

    [xmlParser release]; 

} 


#pragma - 
#pragma TableView 

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [appDelegate.newsArray count]+1; 

} 


// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *postCellId = @"postCell"; 
    static NSString *moreCellId = @"moreCell"; 
    UITableViewCell *cell = nil; 

    NSUInteger row = [indexPath row]; 
    NSUInteger count = [appDelegate.newsArray count]; 

    if (row == count) { 

     cell = [tableView dequeueReusableCellWithIdentifier:moreCellId]; 
     if (cell == nil) { 

      if (cell == nil) { 
       [[NSBundle mainBundle] loadNibNamed:@"TableCell103" owner:self options:NULL]; 
       cell = nibLoadedCell; 
      } 

     } 

    } else { 

     cell = [tableView dequeueReusableCellWithIdentifier:postCellId]; 
     if (cell == nil) { 
      [[NSBundle mainBundle] loadNibNamed:@"TableCell13" owner:self options:NULL]; 
      cell = nibLoadedCell; 
     } 

     aNewsInfo = [appDelegate.newsArray objectAtIndex:indexPath.row]; 
     titleLabel.text = [aNewsInfo.title stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
     imageLabel.image = aNewsInfo.smallImageData; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 

    return cell; 
} 


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    NSLog(@" Global %d",global); 

    NSUInteger row = [indexPath row]; 
    NSLog(@"%d",row); 

    NSUInteger count = [appDelegate.newsArray count]; 
    NSLog(@"Ini AppDelegate Count %d",count); 

    if (row == count) { 


     NSMutableArray *newPosts = [[NSArray alloc] initWithArray:appDelegate.newsArray]; 
     NSUInteger newCount = [newPosts count]; 
     NSLog(@"NewPost %d",newCount); 

     selectedLanguage = global; 
     IDValue = IDValue +1; 
     textLabel.text=[self languageSelectedStringForKey:@"Welcome to Advance Localization"]; 

     if (newPosts) { 
      [appDelegate.newsArray addObjectsFromArray:newPosts]; 

      NSUInteger countOne = [appDelegate.newsArray count]; 
      NSLog(@"appdelegate+newPosts %d",countOne); 
      NSUInteger newCountTwo = [newPosts count]; 
      [newPosts release]; 
      NSLog(@"NewPost %d",newCountTwo); 
      NSMutableArray *insertIndexPaths = [NSMutableArray array]; 

      for (NSUInteger item = newCount; item < countOne; item++) { 

       [insertIndexPaths addObject:[NSIndexPath indexPathForRow:item 
                   inSection:0]]; 
      } 

      [myTableView beginUpdates]; 
      [myTableView insertRowsAtIndexPaths:insertIndexPaths 
            withRowAnimation:UITableViewRowAnimationFade]; 
      [myTableView endUpdates]; 

      [myTableView scrollToRowAtIndexPath:indexPath 
            atScrollPosition:UITableViewScrollPositionNone 
              animated:YES]; 

      NSIndexPath *selected = [myTableView indexPathForSelectedRow]; 
      if (selected) { 
       [myTableView deselectRowAtIndexPath:selected animated:YES]; 
      } 

     } 

    } 
    else { 

     ndvController = [[DetailNewsDisplayController alloc] initWithNibName:@"DetailNewsDisplayController" bundle:[NSBundle mainBundle]]; 
     aNewsInfo = [appDelegate.newsArray objectAtIndex:indexPath.row]; 

     ndvController.aNewsInfo = aNewsInfo; 

     [[self navigationController] pushViewController:ndvController 
               animated:YES]; 
     [ndvController release]; 
    } 
} 


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




@end 

回答

0

當你arereloading的實現代碼如下,你必須增加沒有行的。