How to use arrayWithContentsOfFile to load file successfully written with writeToFile in ObjectiveC/XCode

后端 未结 2 404
孤街浪徒
孤街浪徒 2021-01-18 06:42

I am saving an array of custom objects to a plist list file like so:

+(void) arrayToPlist: (NSArray*) plant_types{
    NSMutableArray* dictionary_array = [NS         


        
2条回答
  •  鱼传尺愫
    2021-01-18 07:35

    With your plist, this code return a correct result

    +(NSMutableArray*) arrayFromPlist{
        NSLog(@"Loading array of plant types from plist.");
    
        NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString* filePath    = [rootPath stringByAppendingPathComponent:@"PlantTypes.plist"];
        NSFileManager*  fileManager = [NSFileManager defaultManager];
    
        if([fileManager fileExistsAtPath:filePath]){ 
            NSLog(@"Plist file exists at expected location.");
            NSMutableArray* plant_dicts = [NSMutableArray arrayWithContentsOfFile:filePath];
            NSLog(@"Loaded array with contents of file, got %d plant types.", plant_dicts.count);
            NSMutableArray* plant_types = [NSMutableArray arrayWithCapacity: plant_dicts.count];
            for(int i = 0; i< plant_dicts.count; i++){
                NSMutableDictionary* dict = [plant_dicts objectAtIndex: i];
                [plant_types addObject: dict];
            }
            return plant_types;
        }
        NSLog(@"Plant Type plist file not found.");
        return NULL;
    }
    

    result

    2012-02-22 16:24:43.697 Test[5574:10103] Loading array of plant types from plist.
    2012-02-22 16:24:43.698 Test[5574:10103] Plist file exists at expected location.
    2012-02-22 16:24:43.699 Test[5574:10103] Loaded array with contents of file, got 5 plant types.
    2012-02-22 16:24:43.700 Test[5574:10103](
            {
            name = "Autumn Olive";
            radius = 10;
        },
            {
            name = "Dwarf Cherry";
            radius = 5;
        },
            {
            name = Bamboo;
            radius = 2;
        },
            {
            name = Pomegranate;
            radius = 6;
        },
            {
            name = Lupin;
            radius = "0.6000000238418579";
        }
    )
    

    I think problem come from your PlantType implementation. Can you post your code (toDict and fromDict methods)

提交回复
热议问题