NSMutableArray的NSInternalInconsistencyException(NSInternalInconsistencyException for NSMutableArray)

我正在尝试将对象添加到NSMutableArray但它一直给我这个错误:

NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object

我已经研究过这个问题了,我没有做过去做过的任何错事,所以我不知道出了什么问题。 这是我的代码:

Group.h

@property (strong, nonatomic) NSString *custom_desc;
@property (strong, nonatomic) NSMutableArray *attributes; //I define the array as mutable

Group.m

#import "Group.h"

@implementation Group
-(id)init
{
    self = [super init];
    if(self)
    {
        //do your object initialization here
        self.attributes = [NSMutableArray array]; //I initialize the array to be a NSMutableArray
    }
    return self;
}
@end

GroupBuilder.m

#import "GroupBuilder.h"
#import "Group.h"

@implementation GroupBuilder
+ (NSArray *)groupsFromJSON:(NSData *)objectNotation error:(NSError **)error
{
    NSError *localError = nil;
    NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];

    if (localError != nil) {
        *error = localError;
        return nil;
    }

    NSMutableArray *groups = [[NSMutableArray alloc] init];
    NSDictionary *results = [parsedObject objectForKey:@"result"];
    NSArray *items = results[@"items" ];

    for (NSDictionary *groupDic in items) {
        Group *group = [[Group alloc] init];
        for (NSString *key in groupDic) {
            if ([group respondsToSelector:NSSelectorFromString(key)]) {
                [group setValue:[groupDic valueForKey:key] forKey:key];
            }
        }
        [groups addObject:group];
    }
    for(NSInteger i = 0; i < items.count; i++) {
        //NSLog(@"%@", [[items objectAtIndex:i] objectForKey:@"attributes"]);
        NSMutableArray *att = [[items objectAtIndex:i] objectForKey:@"attributes"]; //this returns a NSArray object understandable
        Group *g = [groups objectAtIndex:i];
        [g.attributes addObjectsFromArray:[att mutableCopy]]; //I use mutable copy here so that i'm adding objects from a NSMutableArray and not an NSArray
    }

    return groups;
}
@end

I'm trying to add objects to an NSMutableArray but it keeps giving me this error.:

NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object

I have researched this problem, and I'm not doing anything wrong that past people have done, so I have no idea what's wrong. Here is my code:

Group.h

@property (strong, nonatomic) NSString *custom_desc;
@property (strong, nonatomic) NSMutableArray *attributes; //I define the array as mutable

Group.m

#import "Group.h"

@implementation Group
-(id)init
{
    self = [super init];
    if(self)
    {
        //do your object initialization here
        self.attributes = [NSMutableArray array]; //I initialize the array to be a NSMutableArray
    }
    return self;
}
@end

GroupBuilder.m

#import "GroupBuilder.h"
#import "Group.h"

@implementation GroupBuilder
+ (NSArray *)groupsFromJSON:(NSData *)objectNotation error:(NSError **)error
{
    NSError *localError = nil;
    NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];

    if (localError != nil) {
        *error = localError;
        return nil;
    }

    NSMutableArray *groups = [[NSMutableArray alloc] init];
    NSDictionary *results = [parsedObject objectForKey:@"result"];
    NSArray *items = results[@"items" ];

    for (NSDictionary *groupDic in items) {
        Group *group = [[Group alloc] init];
        for (NSString *key in groupDic) {
            if ([group respondsToSelector:NSSelectorFromString(key)]) {
                [group setValue:[groupDic valueForKey:key] forKey:key];
            }
        }
        [groups addObject:group];
    }
    for(NSInteger i = 0; i < items.count; i++) {
        //NSLog(@"%@", [[items objectAtIndex:i] objectForKey:@"attributes"]);
        NSMutableArray *att = [[items objectAtIndex:i] objectForKey:@"attributes"]; //this returns a NSArray object understandable
        Group *g = [groups objectAtIndex:i];
        [g.attributes addObjectsFromArray:[att mutableCopy]]; //I use mutable copy here so that i'm adding objects from a NSMutableArray and not an NSArray
    }

    return groups;
}
@end

原文:https://stackoverflow.com/questions/23721380
2019-11-18 15:05

满意答案

Mongo的函数是异步的。 在connect回调中的任何代码完成之前,您正在关闭db连接。

insert的回调中更改db.close()调用。

router.post('/adduser', function (req, res, next) {
    var _username = req.body.username;
    var _password = req.body.password;
    var url = 'mongodb://localhost:27017/interview_prac';

    MongoClient.connect(url, function (err, db) {
        //if we didn't connect, throw error
        if (err)
            throw err;
        console.log("connected")

        var users = db.collection('Users')
            users.findOne({
                name: _username
            }, function (err, user) {
                if (user) {
                    err = 'The username already exists'
                        res.render('about', {
                            msg: err
                        })
                } else {
                    users.insert({
                        name: _username,
                        password: _password
                    }, function (err, result) {
                        db.close()
                        console.log("Database closed")
                        console.log("entry saved")
                        var new_msg = "Welcome " + _username
                            res.render('about', {
                                msg: new_msg
                            })
                    })
                }
            })
    })
})

Mongo's functions are asynchronous. You're closing the db connection before it has even done any of the code inside your connect callback.

Change your db.close() call inside the insert's callback.

router.post('/adduser', function (req, res, next) {
    var _username = req.body.username;
    var _password = req.body.password;
    var url = 'mongodb://localhost:27017/interview_prac';

    MongoClient.connect(url, function (err, db) {
        //if we didn't connect, throw error
        if (err)
            throw err;
        console.log("connected")

        var users = db.collection('Users')
            users.findOne({
                name: _username
            }, function (err, user) {
                if (user) {
                    err = 'The username already exists'
                        res.render('about', {
                            msg: err
                        })
                } else {
                    users.insert({
                        name: _username,
                        password: _password
                    }, function (err, result) {
                        db.close()
                        console.log("Database closed")
                        console.log("entry saved")
                        var new_msg = "Welcome " + _username
                            res.render('about', {
                                msg: new_msg
                            })
                    })
                }
            })
    })
})

相关问答

更多

MongoDB - 如果不存在则插入,否则跳过(MongoDB- Insert if it doesn't exist, else skip)

根据你想要处理的事情,你有两个真正的选择: 如果密钥数据存在,使用MongoDB的upsert功能实质上“查找”。 如果没有,那么你只传入数据到$setOnInsert ,并且不会触及其他任何东西。 批量使用“未订购”操作。 即使返回错误,整批更新也会继续,但错误报告就是这样,并且任何不是错误的都将被排除。 整个例子: var async = require('async'), mongoose = require('mongoose'), Schema = mongoose.Sc...

MongoDB - 如何查询集合中的嵌套项目?(MongoDB - how to query for a nested item inside a collection?)

使用点符号(例如advertisers.name )从嵌套对象查询和检索字段: db.agencies.find( { "advertisers.created_at" : {$gte : start , $lt : end} } , { _id : 1 , program_ids : 1 , "advertisers.name": 1 } } ).limit(1).toArray(); 参考: 检索字段和点符号 的子集 Use dot notation (e.g. advertisers.n...

Mongodb不会将项目插入集合中(Mongodb doesn't insert item into collection)

Mongo的函数是异步的。 在connect回调中的任何代码完成之前,您正在关闭db连接。 在insert的回调中更改db.close()调用。 router.post('/adduser', function (req, res, next) { var _username = req.body.username; var _password = req.body.password; var url = 'mongodb://localhost:27017/intervi...

php-insert数组中的mongodb到mongo db集合(mongodb in php-insert array to mongo db collection)

我假设您的问题是文档中的子项字段在插入数据库时永远不会包含多个键/值对。 for($i=1;$i<=$subitem_num;$i++){ ${"subitem_name$i"} = data::test_input($_POST["subitem_name".$i]); ${"subitem_file$i"} = data::test_input($_POST["subitem_file".$i]); if(count($errors)==0){ $subitem...

无法使用Meteor在MongoDB中创建空集合(Can not create empty collection in MongoDB using Meteor)

来自流星,没有。 您可以使用db.createCollection从mongo shell创建一个空集合 否则只需插入一个文档,然后按照@CodeChimp的建议立即将其删除 From Meteor, no. You can create an empty collection from the mongo shell using db.createCollection Otherwise just insert a doc and remove it right away as suggeste...

在mongodb db中解析错误,插入到具有唯一索引的集合中(Parsing error in mongodb db, insert to collection with unique index)

http://godoc.org/labix.org/v2/mgo#IsDup func IsDup(err error) bool IsDup返回err是否通知重复键错误,因为主键索引或辅助唯一索引已经具有给定值的条目。 例如 err := users.Insert(user) // where user is type *mgo.Collection if err != nil { if mgo.IsDup(err) { // Is a duplicate key, b...

PHP中的MongoDB - 如何将项目插入到集合中的数组中?(MongoDB in PHP - How do I insert items into an array in a collection?)

使用Mongo的$push操作: $new_task = array( "task" => "do even more stuff", "comment" => "this is the new task added" ); $collection->update( array("_id" => ObjectId("4d8653c027d02a6437bc89ca")), array('$push' => array("tasks" => $new_task)) ); Use ...

检查项目集合值mongodb(check an item collection value mongodb)

var collection = db.get('usercollection'); collection.count({username:username}, function(err, count){ if(err){ return callback(err); } if(count > 0){ return callback('User already exists!'); } //do your insert operation }); var ...

MongoDB - 如何将位置插入集合(MongoDB - how to insert a location into collection)

你必须创建坐标的jsonarray,然后将它放在jsonObject中。 尝试这样的事情: double latLong[] = {124.6682391, -17.8978304}; JSONArray jsonArray = new JSONArray(latLong); JSONObject jobj = new JSONObject().put("type", "point"); jobj.put("coordinates",...

如何从集合中插入多个文档作为另一个文档中的数组字段 - MongoDB(How to insert multiple documents from a collection as an array field in another document - MongoDB)

我想通了:我需要添加标志: db.results.update({"id": 2}, {$push: {"arr": doc }}, true, false) I figured it out: I needed to add flags: db.results.update({"id": 2}, {$push: {"arr": doc }}, true, false)

相关文章

更多

IOS高访微信聊天对话界面(sizeWithFont:constrainedToSize和stretchableImageWithLeftCapWidth的使用)

大家好,百忙之中,抽出点空,写个微博,话说好久没写。 最近项目中有碰到写类似微信聊天界面上的效果,特整 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本