I'm an Android dev who's recently started IOSing. In all my of my Android projects, I have an IO class that does the following:
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;
}
and the equivalent for save. It works great, I can load and save instances from anything with it.
In Objective C, I'm using NSKeyedArchiver/NSKeyedUnarchiver. Archiving seems to work, but unarchiving causes this:
*** -[NSKeyedUnarchiver initForReadingWithData:]: data is empty; did you forget to send -finishEncoding to the NSKeyedArchiver?
I'm using the following static methods:
+(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;
}
and
+(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;
}
I'm calling them as such
[IVIO saveObject:thing forKey:@"thekey"];
Thing *miracle = [IVIO loadForKey:@"thekey"];
What's going on?
Thank you
In your +loadForKey:
NSMutableData *bytes = [NSMutableData data];
NSKeyedUnarchiver *unrar = [[NSKeyedUnarchiver alloc] initForReadingWithData:bytes];
you're trying to read from an empty data object. Creating a mutable data object using [NSMutableData data]
just gives you an object that contains nothing. You'll need to READ the data from somewhere. Likewise, in your +saveObject:forKey:
you successfully archive the object, but you don't do anything with the resulting data object.
To fix, you'll want to write the data into a file or URL in your save method, and read it from a file or URL in your load method.
精彩评论