How to save NSMutablearray in NSUserDefaults

前端 未结 9 1175
盖世英雄少女心
盖世英雄少女心 2020-11-29 17:50

I have two NSMutableArray\'s. They consist of images or text. The arrays are displayed via a UITableView. When I kill the app the data within the <

9条回答
  •  臣服心动
    2020-11-29 18:02

    Do you really want to store images in property list? You can save images into files and store filename as value in NSDictionary.

    define path for store files

    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    self.basePath = [paths firstObject];
    

    Store and load image:

    
    - (NSString *)imageWithKey:(NSString)key {
        NSString *fileName = [NSString stringWithFormat:@"%@.png", key]
        return [self.basePath stringByAppendingPathComponent:fileName];
    }
    
    - (void)saveImage:(UIImage *)image withKey:(NSString)key {
        NSData *imageData = UIImagePNGRepresentation(image);
        [imageData writeToFile:[self imageWithKey:key] atomically:YES];
    }
    
    - (UIImage *)loadImageWithKey:(NSString)key { {
        return [UIImage imageWithContentsOfFile:[self imageWithKey:key]];
    }
    

    And you can store path or indexes in NSMutableDictionary

    
    - (void)saveDictionary:(NSDictionary *)dictionary {
        NSMutableDictionary *dictForSave = [@{ } mutableCopy];
        for (NSString *key in [dictionary allKeys]) {
            [self saveImageWithKey:key];
            dictForSave[key] = @{ @"image" : key };
        }
        [[NSUserDefaults standardUserDefaults] setObject:dictForSave forKey:@"MyDict"];
    }
    
    - (NSMutableDictionary *)loadDictionary:(NSDictionary *)dictionary {
        NSDictionary *loadedDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyDict"];
        NSMutableDictionary *result = [@{ } mutableCopy];
        for (NSString *key in [loadedDict allKeys]) {
            result[key] = [self imageWithKey:key];
        }
        return result;
    }
    

    In NSUserDefaults you can store only simply objects like NSString, NSDictionary, NSNumber, NSArray.

    Also you can serialize objects with NSKeyedArchiver/NSKeyedUnarchiver that conforms to NSCoding protocol .

提交回复
热议问题