2013-01-14 3 views
1

NSMutableArray을 사용하여 채울 UITableView이 있습니다. 이 tableview은 스크롤 할 때 업데이트되며 NSMutableArray에 더 많은 데이터를 추가하여 업데이트됩니다. 내가 직면하고있는 문제는이 페이지에서 다른 페이지로 이동 한 다음 다시 돌아올 때마다 tableview이 배열의 초기 크기로 설정된다는 것입니다. 얼마나 많은 업데이트를 수행하든 (즉, 매번 10 개의 객체를로드하면, 테이블 크기는 배열 크기가 30 인 경우에도 10으로 되돌아갑니다. 참고 : 배열 크기는 테이블 내용 크기 만 변경하지 않습니다. 나는 이것이 NSMutableArray의 속성과 관련이 있다고 믿기 시작했습니다. 코드의 요점은 이것이다 :NSMutableArray 속성은 UITableView를 채 웁니다.

@interface FlowViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> 
{ 
    UITableView *flowTable; 

    NSMutableArray *cellData; 

} 
@property(nonatomic, retain) IBOutlet UITableView *flowTable; 

@property(nonatomic, retain) NSMutableArray *cellData; 

- (void) getData; 
- (void) storeData: (NSMutableArray*) arr; 

@end 

@implementation FlowViewController 

@synthesize cellData; 

@synthesize flowTable; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.flowTable.autoresizingMask = UIViewAutoresizingFlexibleHeight; 

    [self.flowTable setDataSource:self]; 
    [self.flowTable setDelegate:self]; 

    self.cellData = [[NSMutableArray alloc] init]; 

    [self getData]; 
} 

- (void) storeData:(NSMutableArray *)arr 
{ 
    for(NSDictionary *data in arr) 
    { 

     CellObject *det = [[CellObject alloc] init]; 

     // store details 

     [self.cellData addObject: det]; 

    } 

    [self.flowTable reloadData]; 
} 

- (void) getData 
{ 

    NSString *url = @"http://example.com/"; 

    NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] 
                  cachePolicy:NSURLRequestUseProtocolCachePolicy 
                timeoutInterval:10.0]; 

[theRequest setHTTPMethod:@"GET"]; 

flowConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 

} 


#pragma mark - 
#pragma mark Table View Data Source Methods 

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return [self.cellData count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *CellIdentifier = @"FlowCell"; 

    MyFlowCell *cell = (MyFlowCell *)[self.flowTable dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 

     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FlowCell" owner:nil options:nil]; 
     // cell = [nib objectAtIndex:0]; 

     for(id currentObject in nib) 
     { 

     if([currentObject isKindOfClass:[MyFlowCell class]]) 

     { 
      cell = (MyFlowCell *)currentObject; 

     break; 
    } 
    } 

    cell.selectionStyle = UITableViewCellSelectionStyleNone; 

} 

CellObject *rowItem = [cellData objectAtIndex:indexPath.row]; 

    // set cell data 

} 

    return cell; 
} 


- (void)tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
[tableView deselectRowAtIndexPath:indexPath animated:YES]; 

    self.current = indexPath.row; 

    [self performSegueWithIdentifier:@"flowToAnotherSegue" sender:nil]; 

} 


- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 

    if ([segue.identifier isEqualToString:@"flowToAnotherSegue"]) 
    { 
     NewViewController *iv = 
      segue.destinationViewController; 

    iv.current = self.current; 
     iv.data = self.cellData; 

    } 

} 


#pragma mark - 
#pragma NSURLConnection Delegate Methods 
- (void) connection:(NSURLConnection *)_connection didReceiveResponse:(NSURLResponse *)response { 
    NSLog(@"Receiving response: %@, status %d", [(NSHTTPURLResponse*)response allHeaderFields],  [(NSHTTPURLResponse*) response statusCode]); 
    receivedData = [NSMutableData data]; 
} 

- (void) connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error { 
    NSLog(@"Connection Failed: %@", error); 
} 

- (void) connection:(NSURLConnection *)_connection didReceiveData:(NSData *)_data { 

     [receivedData appendData:_data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 

    // get the new NSMutableArray from receivedData 

    [self storeData: newMutableArray]; 

} 


#pragma mark - 
#pragma mark Deferred image loading (UIScrollViewDelegate) 

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView { 

    if(Bottom reached) { 

     // load more data 

     [self getData]; 

     } 

    } 
} 

@end 

내가 그 너무 많이하지 않습니다 바랍니다. 내가 어디로 잘못 가고 있는지 말해주세요.

답변

0

내 코드에서 무슨 일이 잘못 찾을 수 없습니다로 appDelegate.cellData으로, 내가 만든 임시 수정 프로그램을 대체합니다. 내가 말했듯이, NSMutableArray cellData는 변경되지 않지만, 변경되는 유일한 것은 UITableView 자체입니다 (이건 내 viewDidDisappear 메소드에서 발견되었습니다). 그래서 이것을 보상하기 위해 방금했습니다.

- (void) viewDidAppear:(BOOL)animated 
{ 
    [self.flowTable reloadData]; 

    [self.flowTable scrollToRowAtIndexPath: lastIndex atScrollPosition:0 animated: NO]; 

} 

이렇게하면 마지막으로 선택한 셀로 flowTable을 반환합니다. 그것은 우아하지 않지만 작동합니다. 아이디어를 계속 게시하십시오. 나는 정말로 이것의 바닥에 가고 싶다.

1

공유 클래스/싱글 톤 클래스에 배열을 저장하십시오.

이 페이지를 다시로드 할 때마다 viewDidLoad이 호출되고 배열에 alloc + init이 다시 수행되어 기본값으로 설정됩니다.

+0

'정적'배열을 잘못된 방법으로 사용하고 거의 항상 잘못된 대답으로 만듭니다. 배열은 지속되는 클래스에서 ivar로 정의되어야합니다. – zaph

+0

내가 말했듯이, 배열의 크기는 동일하게 유지되며 UITableView의 크기 만 변경됩니다. NSLog 문을 사용하여이를 확인했습니다. –

+0

@Zaph, cellDataVIar (nonatomic, retain) 이외의 속성을 설정해야합니까? –

0

당신이보기가 부하를 한에서 self.cellData = [[NSMutableArray alloc] init];을 삭제하고 JIT 방식으로 자신의 게터를 만드는 경우 : FlowController가 해제 될 때까지 cellData의

-(NSMutableArray *)cellData 
{ 
    if(!_cellData){ 
     _cellData = [NSMutableArray array]; 
    } 
    return _cellData; 
} 

내용이 유지됩니다.

+0

흠. 이것은 작동하지 않았다. 어떤 이유로 든 실행은 if 문을 지나치지 않았습니다. –

0

배열을 viewDidLoad에서 다시 만들고있는 중입니다. 할당하기 전에 이미 배열이 있는지 확인할 수 있습니다.

if (!self.cellData) { 
    self.cellData = [[NSMutableArray alloc] init]; 
    [self getData]; 
} 
+0

그렇다면 내 viewDidLoad 메서드의 NSLog 문을 호출하면 안됩니까? 또한 UITableView에서이 변경 사항은 viewDidDisappear 메서드 (여기서는 표시되지 않음)보다 먼저 발생합니다. 따라서 "tableViewdidSelectRowAtIndexPath"와 "viewDidDisappear"사이에서 변경이 일어나고 있습니다. –

+0

그런 경우 새로운 시각에서 iv.data로 무엇을하고 있습니까? –

+0

다른 스크롤보기에서 사용. 그러나 나는 이것이 그것이 어떤 식 으로든 영향을 미치지 않는다고 생각합니다. 나는 어떤 데이터도 전달하지 않는 헤더 필드와는 다른 버튼으로 다른 segue를 가지고있다. 그리고이 문제는 내가 그 관점에서 돌아올 때에도 발생합니다. –

1

공유 클래스/싱글 톤 클래스에 배열을 저장하십시오. 나만의 공유 클래스를 만들거나 appDelegate을 사용할 수 있습니다.

  • appDelegate에 NSMutableArray 속성을 선언하십시오. @property (nonatomic, strong) NSMutableArray *cellData; 을 합성하고 합성한다.

  • cellData 배열 대신이 배열을 사용하십시오. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];self.cellData

+0

appDelegate의 ivars는 작동하지 않았다. 나는 두려워한다. :( –

관련 문제