目标C:序列化/存档问题

时间:2011-09-28 18:59:53

标签: java objective-c ios serialization archive

我是最近开始使用IOSing的Android开发者。在我的所有Android项目中,我都有一个执行以下操作的IO类:

public static Object load(String fname , Context cont)
{
    FileInputStream fis = cont.openFileInput(fname);
    ObjectInputStream ois = new ObjectInputStream(fis);
    Object loadedObject = ois.readObject();
    ois.close();
    fis.close();
    Father.print("Loaded from file "+fname+" successfully");
    return loadedObject;
}   

和保存的等价物。它工作得很好,我可以用任何东西加载和保存实例。

在Objective C中,我使用的是NSKeyedArchiver / NSKeyedUnarchiver。归档似乎有效,但是归档会导致这种情况:

*** -[NSKeyedUnarchiver initForReadingWithData:]: data is empty; did you forget to send -finishEncoding to the NSKeyedArchiver?

我正在使用以下静态方法:

+(BOOL)saveObject: (id<NSCoding>)obj forKey:(NSString*)key;
{
        NSKeyedArchiver *archiver;
        NSMutableData *bytes = [NSMutableData data];
        archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:bytes];
        [archiver encodeObject:obj forKey:key];
        [archiver finishEncoding];
        NSLog(@"Successfully saved object <%@> to %@", obj, key);
        return TRUE;
}

+(id)loadForKey:(NSString*)key
{
    NSMutableData *bytes = [NSMutableData data];
    NSKeyedUnarchiver *unrar = [[NSKeyedUnarchiver alloc] initForReadingWithData:bytes];
    id result = [unrar decodeObjectForKey:key];
    [unrar finishDecoding];
    NSLog(@"Successfully loaded object <%@>", result);

    return result;
}

我这样称呼他们

[IVIO saveObject:thing forKey:@"thekey"];
Thing *miracle = [IVIO loadForKey:@"thekey"];

发生了什么事?

谢谢

1 个答案:

答案 0 :(得分:1)

+loadForKey:

NSMutableData *bytes = [NSMutableData data];
NSKeyedUnarchiver *unrar = [[NSKeyedUnarchiver alloc] initForReadingWithData:bytes];

您正在尝试从空数据对象中读取数据。使用[NSMutableData data]创建可变数据对象只会为您提供一个不包含任何内容的对象。您需要从某个地方读取数据。同样,在+saveObject:forKey:中,您成功归档了对象,但是您没有对结果数据对象执行任何操作。

要修复此问题,您需要在保存方法中将数据写入文件或网址,并在加载方法中从文件或网址中读取数据。