开发者

NSKeyedUnarchiver chokes when trying to unarchive more than one object

We've got a custom matrix class, and we're attempting to archive and unarchive an NSArray containing four of them. The first seems to get unarchived fine (we can see that initWithCoder is called once), but then the program simply hangs, using 100% CPU. It doesn't continue or output any errors. These are the relevant methods from the matrix class (rows, columns, and matrix are our only instance variables):


-(void)encodeWithCoder:(NSCoder*) coder {
    float temp[rows * columns];
    for(int i = 0; i <开发者_如何学Python; rows; i++) {
        for(int j = 0; j < columns; j++) {
            temp[columns * i + j] = matrix[i][j];
        }

}

[coder encodeBytes:(const void *)temp length:rows*columns*sizeof(float) forKey:@"matrix"];
[coder encodeInteger:rows forKey:@"rows"];
[coder encodeInteger:columns forKey:@"columns"];

}


-(id)initWithCoder:(NSCoder *) coder {
    if (self = [super init]) {
        rows = [coder decodeIntegerForKey:@"rows"];
        columns = [coder decodeIntegerForKey:@"columns"];
        NSUInteger * len;
        *len = (unsigned int)(rows * columns * sizeof(float));
        float * temp = (float * )[coder decodeBytesForKey:@"matrix" returnedLength:len];
        matrix = (float ** )calloc(rows, sizeof(float*));
        for (int i = 0; i < rows; i++) {
            matrix[i] = (float*)calloc(columns, sizeof(float));
        }
        for(int i = 0; i < rows *columns; i++) {
            matrix[i / columns][i % columns] = temp[i];
        }
    }
    return self;
}

And this is really all we're trying to do:


NSArray * weightMatrices = [NSArray arrayWithObjects:w1,w2,w3,w4,nil];
[NSKeyedArchiver archiveRootObject:weightMatrices toFile:@"weights.archive"];
NSArray * newWeights = [NSKeyedUnarchiver unarchiveObjectWithFile:@"weights.archive"];

We've tried archiving one at a time (no NSArray), each to a different file, but it still hangs on the second one.

What's driving us crazy is that we can archive and unarchive a single matrix just fine. We've done so (successfully) with a matrix many times larger than these four combined.


In your initWithCoder method:

NSUInteger * len;
*len = (unsigned int)(rows * columns * sizeof(float));

IN essence you are overwriting your stack, which will cause undefined results.

Should be:

NSUInteger len = (unsigned int)(rows * columns * sizeof(float));
float * temp = (float * )[coder decodeBytesForKey:@"matrix" returnedLength:&len];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜