我有一个小问题,那就是每次我从详细信息视图控制器返回主视图控制器时,都会将重复的数据添加到REALM数据库中。我也尝试替换viewDidLoad中的网络代码,但出现此错误*由于未捕获的异常'RLMException'而终止应用程序,原因:'索引2超出范围*。下面是我的代码:

#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


提前致谢。

最佳答案

您要在viewDidAppear:中添加数据。每次显示视图时都会调用该方法。因此,当用户从局部视图返回此视图时,也将调用它。

而是将其移至viewDidLoad或将代码移至另一个方法,然后仅在需要时才调用它。

如果确实需要在viewDidAppear中包含该代码,并假定已将pageId标记为HomePageList的主键,则可以执行addOrUpdateObject:而不是addObject:。这将确保如果对象已存在于Realm中,则仅更新而不重复。

关于ios - 加载 View 后,将重复数据添加到REALM,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33930269/

10-12 21:35
查看更多