iOS nsmutalblearray addobject程序崩溃

请问NSMutableArray在alloc init之后再调用addobject还是会崩溃的可能原因有哪些?
出现错误:[__NSArrayI addObject:]: unrecognized selector sent to instance 0xb848630'

ChatMessage *newMsg = [[ChatMessage alloc] init];
newMsg.owner = MSG_OWNER_SELF;
newMsg.type = MSG_TYPE_SOUND;
newMsg.timeStamp = self.dateToRecordStr;
newMsg.msg = [NSString stringWithFormat:@"%@%@.aac", self.toChatUsr.UID, newMsg.timeStamp];
[self.toChatUsr.msgs addObject:newMsg];

这是代码
最后一句会崩掉。
toChatUsr是 @property(weak, nonatomic),赋值是 = 一个@property(strong, nonatomic)

chatMsssage的初始化代码

@implementation ChatMessage

  • (id)init{
    self = [super init];
    if (self) {
    self.owner = [[NSString alloc] init];
    self.type = [[NSString alloc] init];
    self.timeStamp = [[NSString alloc] init];
    self.msg = [[NSString alloc] init];
    }

    return self;
    }

阅读 7.4k
5 个回答

mutableArray在用Array赋值时不能直接 = ,这样mutableArray实际上指向的是NSArray,导致后续错误。一般采用nsmutableArray = [[nsmutableArray alloc] initwithArray:array]的形式。

NSArrayI addObject 是不是定义的时候错了?猜的哈

错误提示已经说得很清楚了。
[__NSArrayI addObject:]: unrecognized selector sent to instance 0xb848630'
你访问的实例并不是 NSMutableArray

另外,你应该把关键代码 po 上来

self.toChatUsr.msgs 初始化的代码po上来看看

NSMutableArray继承于NSArray,你是不小心把一个NSArray对象赋值给了一个声明为NSMutableArray的对象,于是在对NSArray对象使用addObject方法时出错。
建议:在把NSArray赋值给NSMutableArray对象时使用
mutableArray = [array mutableCopy];

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题