Search code examples
iosobjective-cplist

NSKeyedUnarchiver. Loading array of custom objects from plist


I am trying to load my .plist fileenter image description here

Into array of my cusom objects, called Property. Here is Property.h:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface Property : NSObject<NSCoding> {
    int price_base;
    float state;
    float infrastructure;
}

-(id)initWithCoder:(NSCoder *)decoder;
-(void)encodeWithCoder:(NSCoder *)aCoder;
@end

And Property.m:

#import "Property.h"

@implementation Property
-(void)encodeWithCoder:(NSCoder *)aCoder 
{/*No need to encode yet*/}
-(id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {

        price_base = [decoder decodeIntForKey:@"price_base"];
        state = [decoder decodeFloatForKey:@"state"];
        infrastructure = [decoder decodeFloatForKey:@"infrastructure"];
    }
    return self;
}
@end

The code, that executes, trying to load objects is next:

-(void)loadProperty
{
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"Property" ofType:@"plist"];
    NSMutableArray *propertyArray = [[NSMutableArray alloc] init];
    propertyArray = [[NSKeyedUnarchiver unarchiveObjectWithFile:resourcePath] mutableCopy];
}

There is an exception, during Runtime, that drops the next:

[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x7f99e5102cc0 2015-04-30 17:40:52.616 RealEstate[5838:2092569] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x7f99e5102cc0'

Does anyone have any idea, what may be wrong with code? I am rather new to XCode and ObjectiveC, so help would be very appreciative!


Solution

  • You are confusing archiving with serialization.

    NSString *resourcePath = 
        [[NSBundle mainBundle] pathForResource:@"Property" ofType:@"plist"];
    NSMutableArray *propertyArray = [[NSMutableArray alloc] init];
    propertyArray = 
        [[NSKeyedUnarchiver unarchiveObjectWithFile:resourcePath] mutableCopy];
    

    That is not how you read a .plist file. It is not archived and you don't need an unarchiver to read it. It is an array so just read it directly into an NSArray (initWithContentsOfFile:).

    In the result, everything will be immutable. If that isn't what you want, you need the NSPropertyListSerialization class to help you.