ios - 加载 View 后将重复数据添加到 REALM

标签 ios objective-c uitableview xcode7 realm

我有一个小问题,就是每次我从细节 View Controller 返回到主视图 Controller 时,我都会将重复数据添加到 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: 中添加数据。每次显示 View 时都会调用该方法。因此,当用户从详细 View 返回到此 View 时,它也会被调用。

相反,将其移动到 viewDidLoad 或将代码移动到另一个方法并仅在需要时调用它。

如果您确实需要在您的 viewDidAppear 中包含该代码,并且假设您已将 pageId 标记为 HomePageList 的主键,您可以执行 addOrUpdateObject: 而不是 addObject:。这将确保如果该对象已经存在于 Realm 中,它只会被更新而不会被复制。

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

相关文章:

ios - 以编程方式自定义 TableViewCell

ios - 如何实现左右滑动以在 swift IOS 中更改数据/ View ?

ios - 行尾在 iPhone 上被截断(编辑 : end of line justification)

ios - 如何在 iOS 中将图像设置为 uialertview 按钮?

ios - UITextView 中链接的不同样式

ios - 如何在 iOS 上实现单点登录

objective-c - AVCaptureVideoPreviewLayer 不适用于 renderInContext

swift - UITableView如何保持滚动到底部[自动滚动]?

ios - 呈现 UIViewController View 的多种方式

iphone - 使用Openears框架进行语音识别?