2015-11-26 53 views
0

我有一個小問題,就是每次我回來,從細節主視圖控制器查看我被添加到數據庫REALM重複數據控制器。我也嘗試更換viewDidLoad中的網絡代碼,但我得到了這個錯誤*由於未捕獲的異常'RLMException',終止應用程序,原因:'索引2超出界限*。下面是我的代碼:重複數據添加到REALM一次查看加載

#import "HomeTVC.h" 
#import "facebook.h" 
#import "HomeTVCell.h" 
#import "MBProgressHUD.h" 
#import "PageVideosCVC.h" 
#import "HomePageList.h" 
#import <SDWebImage/UIImageView+WebCache.h> 

@interface HomeTVC()<UITableViewDataSource, UITableViewDelegate> 
{ 
    NSDictionary *userPageLikesParams; 
    NSMutableArray *pagesInfo; 
    NSArray *pagesInfoFromRealm; 
    facebook *fb; 
    HomePageList *homePageList; 

} 
@end 

@implementation HomeTVC 

- (void) viewDidAppear:(BOOL)animated { 

    [super viewDidAppear:YES]; 

    // Add HUD 
    [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 

    userPageLikesParams = @{@"fields": @"about,name,created_time,picture",@"limit": @"10"} ; 

    fb = [[facebook alloc] init]; 

    [fb getUserPagelikes:userPageLikesParams completionHandler:^(NSDictionary *pagesResult) { 

     if (pagesResult != nil) { 

      [pagesInfo addObjectsFromArray:[pagesResult valueForKeyPath:@"data"]]; 

      //   pagesInfo = pagesResult[@"data"]; 

      // Delete all available data in REALM 

      RLMRealm *realm = [RLMRealm defaultRealm]; 
      [realm beginWriteTransaction]; 
      [realm deleteAllObjects]; 
      [realm commitWriteTransaction]; 

      [realm beginWriteTransaction]; 
      for(NSDictionary *pageInfoToSaveInRealm in pagesInfo){ 
       HomePageList *homePages = [[HomePageList alloc] init]; 
       homePages.pageID = pageInfoToSaveInRealm[@"id"]; 
       homePages.pageName = pageInfoToSaveInRealm[@"name"]; 
       homePages.pageProfilePic = [pageInfoToSaveInRealm valueForKeyPath:@"picture.data.url"]; 
       [realm addObject:homePages]; 

       dispatch_async(dispatch_get_main_queue(), ^{ 
        RLMRealm *realmMainThread = [RLMRealm defaultRealm]; 
        RLMResults *pagesInformation = [HomePageList allObjectsInRealm:realmMainThread]; 
        pagesInfoFromRealm = pagesInformation; 
        NSLog(@"ayam : %d", (int)pagesInfoFromRealm.count); 

        [self.tableView reloadData]; 
        [MBProgressHUD hideHUDForView:self.view animated:YES]; 
       }); 

      } 
      [realm commitWriteTransaction]; 

     } 

    } failure:^(NSError *error) { 
     if(error) { 
      pagesInfoFromRealm = [HomePageList allObjects]; 
      [self.tableView reloadData]; 
      [MBProgressHUD hideHUDForView:self.view animated:YES]; 
     } 
    }]; 

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; 
} 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.tableView.delegate = self; 
    self.tableView.dataSource = self; 

    pagesInfo = [NSMutableArray array]; 

    // [facebook currentFBAccessToken]; 
    // [facebook getFBUserInfo]; 

} 

#pragma mark - Table view data source 

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    if (pagesInfoFromRealm == nil) { 
     return 0; 
    } else { 
     NSLog(@"table count : %d", (int)pagesInfoFromRealm.count); 
     return pagesInfoFromRealm.count; 
    } 

} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"CellIdentifier"; 

    HomeTVCell *cell = (HomeTVCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    // NSLog(@"pagesInfoFromRealm : %@", pagesInfoFromRealm); 

    homePageList = pagesInfoFromRealm[[indexPath item]]; 

    NSURL *imageURL = [NSURL URLWithString:homePageList.pageProfilePic]; 

    // cache the image using sdwebimage 
    cell.pageProfilePic.layer.backgroundColor=[[UIColor clearColor] CGColor]; 
    cell.pageProfilePic.layer.borderWidth = 2.0; 
    cell.pageProfilePic.layer.masksToBounds = YES; 
    cell.pageProfilePic.layer.borderColor=[[UIColor whiteColor] CGColor]; 
    cell.pageProfilePic.layer.cornerRadius= 30.0; 
    [cell.pageProfilePic sd_setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]]; 
    cell.pageName.text = homePageList.pageName; 

    return cell; 
} 

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

    UIStoryboard* sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; 
    PageVideosCVC *pageVideo = [sb instantiateViewControllerWithIdentifier:@"videoDetails"]; 
    homePageList = pagesInfoFromRealm[indexPath.row]; 
    NSLog(@"pagesInfoFromRealm array count: %d", (int)pagesInfoFromRealm.count); 

    NSLog(@"homepagelist data: %@", pagesInfoFromRealm[indexPath.row]); 
    pageVideo.pageID = homePageList[@"pageID"]; 
    pageVideo.pageName = homePageList[@"pageName"]; 
    [self presentViewController:pageVideo animated:YES completion:nil]; 

} 

@end 

在此先感謝。

+0

把你所有的境界代碼到自定義方法eg.'(void)doAfterGetData'或什麼,只有當你需要它時纔會調用它...所以你可以更好地控制它,而不是把它放在'viewdidappear' – Tj3n

回答

2

你在你的viewDidAppear:添加數據。每次顯示視圖時都會調用該方法。所以當用戶從詳細視圖返回到這個視圖時,它也會被調用。

相反,移動這viewDidLoad或代碼移動到另一個方法和僅在需要時調用它。

如果你真的需要有一個代碼在你viewDidAppear,並假設你已經標誌着pageIdHomePageList主鍵,你可以做的,而不是addOrUpdateObject:addObject:。這將確保如果該對象已經存在於Realm中,則只會更新不重複。

0

要確保這是隻執行一次,你可以移動的動作爲isMovingToParent檢查,這是一個特殊的BOOL方法只能在UIViewController轉換使用:

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 

    if ([self isMovingToParentViewController]) { 

     // Action 
    } 
}