NSObject(RACKVOWrapper)rac_observeKeyPath:options:observer:block:EXC_BAD_ACCESS崩溃

时间:2014-03-02 01:24:10

标签: ios uicollectionview reactive-cocoa

我正在使用ReactiveCocoa使UICollectionView与消息列表保持同步。我的模型收到新消息后,在尝试更新我的集合视图时发生崩溃。

这是我的视图模型,它通过来自套接字客户端的委托调用获取更新。

@interface ConversationViewModel : NSObject

@property (nonatomic, strong) NSMutableArray *messages;

- (RACSignal *)rac_signalForMessageReceived;

@end

@implementation ConversationViewModel
....
- (void)client:(PSClient *)theClient didReceiveMessage:(PSMessage *)aMessage {
    [self.messages addObject:aMessage];
    [_messageReceivedSubscriber sendNext:nil]; 
}
....
- (RACSignal *)rac_signalForMessageReceived {
    RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        self.messageReceivedSubscriber = subscriber;
        return [RACDisposable disposableWithBlock:^{
            self.messageReceivedSubscriber = nil;
            // Do Nothing
        }];
    }];

    [signal setName:@"rac_signalForMessageReceived"];

    return signal;
}

消息对象是

@interface Message : NSObject

@property (nonatomic, assign) NSString *message;
@property (nonatomic, assign) NSString *name;

@end

以下是控制器如何使用它。

- (void)viewDidLoad
    [super viewDidLoad];

    [self.conversationViewModel.rac_signalForMessageReceived subscribeNext:^(PSMessage *message) {
        [self.collectionView reloadData];
    }];

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.conversationViewModel.messages count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    PSConversationMessageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"conversationCell" forIndexPath:indexPath];

    [cell setMessage:self.conversationViewModel.messages[indexPath.row]];

    return cell;
}

最后,这是我在细胞内进行绑定的方法。

- (void)awakeFromNib {
    RAC(self.messageLabel, text) = RACObserve(self, message.message);
    RAC(self.nameLabel, text) = RACObserve(self, message.name);
}

一旦集合视图重新加载,我在rac_observeKeyPath中得到一个异常:options:observer:block:。在屏幕截图中可以看到堆栈。 enter image description here

有谁知道为什么会导致异常?或者更好的方法来处理在ConversationViewModel中接收消息?

1 个答案:

答案 0 :(得分:2)

我找到了不寻常的崩溃的原因。我的消息对象使用NSString属性的assign属性类型。它需要复制。花了很长时间跟踪那个人。