使用Objective-C的Realm和tableView iOS应用程序:线程1 EXC_BAD_ACCESS(代码=,地址= 0x30)

时间:2015-11-07 08:54:25

标签: ios objective-c uitableview realm

我想将我的realm数据库加载到我的tableView中,我的代码是这样的:

#import "ViewController.h"
#import "customCell.h"
#import "Person.h"

@interface ViewController ()
@property RLMRealm *realm;
@property RLMResults *person;
@end

@implementation ViewController
@synthesize realm, person;
- (void)viewDidLoad {
    [super viewDidLoad];
    Person *one;
    one.firstName = @"Allen";
    one.lastName = @"X";
    realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    [realm addObject:one];
    [realm commitWriteTransaction];
    self.person = [Person allObjects];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:   (NSInteger)section{
    return [person count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSString *cellIdentifier = @"cellIdentifier";
    customCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.firstName.text = [self.person[indexPath.row] firstName];
    cell.lastName.text = [self.person[indexPath.row] lastName];
    return cell;
}

@end

我认为这里可以省略Person.h。 所以每次我编译运行它都会这样说: enter image description here

我试了几千次,从来没有弄明白为什么。有人可以帮助这个可怜的新秀吗?

所以在听完你的建议之后,红色错误消失了,但是绿色错误来了。这是:

enter image description here

1 个答案:

答案 0 :(得分:0)

您尚未初始化并分配Person对象,然后您尝试填充其属性,因此您显然遇到了访问冲突。

改为这样:

Person *one = [Person new];
one.firstName = @"Allen";
one.lastName = @"X";