I've got an app that's got an activity/timeline like view. Since I don't want to retrieve the entire timeline every time, I'm caching all the events.
Currently, this is how I go about it:
- (void)saveEventArray:(NSMutableArray *)eventArray {
// save hier in bg
dispatch_async(kAsyncQueue, ^{
__block int loopCount = 0;
NSArray *copyEventArray = [eventArray copy];
NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:copyEventArray.count];
if([copyEventArray count] == 0){ // If it's an empty array to save, it won't loop
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:[[NSMutableArray alloc]init] forKey:@"events"];
NSLog(@"save is done, no events left in eventarray");
}
for (NSMutableDictionary *event in copyEventArray) {
// PFFile isn't easy to encode, but UIImage is, so whenever we encounter a PFFile, we convert it to UIImage
id imageFile = [event objectForKey:@"img"];
if([imageFile isKindOfClass:[PFFile class]]){
[imageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
UIImage *image = [UIImage imageWithData:imageData];
[event setObject:image forKey:@"img"]; // the PFFile is now replaced for an UIImage
NSData *eventEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:event];
[archiveArray addObject:eventEncodedObject];
loopCount++;
if(loopCount == [copyEventArray count]){ // when done looping, save it all
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:archiveArray forKey:@"events"];
NSLog(@"save is done");
}
}
}];
} else {
loopCount++;
NSData *eventEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:event];
[archiveArray addObject:eventEncodedObject];
if(loopCount == [copyEventArray count]){ // when done looping
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:archiveArray forKey:@"events"];
NSLog(@"save is done");
}
}
}
});
}
However, I noticed that this takes insane amounts of storage and the app grows very quickly in size when doing this. Is there a better/more efficient way for this?
UIImage
object? As a .png? As a .jpg? \$\endgroup\$PFFile
is and its documentation? \$\endgroup\$