如何将plist数据读入数据模型?

时间:2011-09-14 20:20:18

标签: iphone ios xcode

我通过在我的数据模型中硬编码一些静态数据(酒店信息)来启动我的应用程序,以便在我的应用程序中随处可访问它们。这个很好,直到列表开始增长(仍然是静态数据)。我试图找出如何使用plist重新创建硬编码数据。似乎直截了当但似乎无法弄明白。

我的“酒店”对象标题:

@interface Hotel : NSObject {}

@property (nonatomic, assign) int HotelID;
@property (nonatomic, copy) NSString* Name;
@property (nonatomic, copy) int Capacity;

@end

我的“酒店”对象实施:

@implementation Hotel

@synthesize HotelID, Name, Capacity;

-(void)dealloc {
    [Name release];
    [Capacity release];
}

“Hotel”对象由我的DataModel管理。 DataModel的标头:

@class Hotel;

@interface DataModel : NSObject {}

-(int)hotelCount;

DataModel实现:

#import "DataModel.h"
#import "Hotel.h"

// Private methods
@interface DataModel ()

@property (nonatomic, retain) NSMutableArray *hotels;

-(void)loadHotels;

@end

@implementation DataModel

@synthesize hotels;

- (id)init {
    if ((self = [super init])) {
        [self loadHotels];
    }
    return self;
}

- (void)dealloc {
    [hotels release];
    [super dealloc];
}

- (void)loadHotels

hotels = [[NSMutableArray arrayWithCapacity:30] retain];

Hotel *hotel = [[Hotel alloc] init];
hotel.HotelID = 0;
hotel.Name = @"Solmar";
hotel.Capacity = 186;
// more data to be added eventually
[hotels addObject:hotel];
[hotel release];

Hotel *hotel = [[Hotel alloc] init];
hotel.HotelID = 1;
hotel.Name = @"Belair";
hotel.Capacity = 389;
[hotels addObject:hotel];
[hotel release];

// and so on... I have 30 hotels hard coded here.

- (int)hotelCount {
    return self.hotels.count;
}

@end

此设置正常。但是,我无法弄清楚如何实现数据硬编码的loadHotel部分。我想用具有相同信息的plist替换它。如何读取plist文件以为每个键(名称,容量等)分配信息?

2 个答案:

答案 0 :(得分:4)

创建plist后,可以将其内容加载到如下字典中:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:plistFileName ofType:nil];
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];

然后,您可以使用plist中的键查询所需的任何数据:

NSArray *hotelsFromPlist = [plistDict objectForKey:"hotels"];

// remember this is autoreleased, so use alloc/initWithCapacity of you need to keep it
NSMutableArray *hotels = [NSMutableArray arrayWithCapacity:[hotelsFromPlist count]];

for (NSDictionary *hotelDict in hotelsFromPlist) {
    Hotel *hotel = [[Hotel alloc] init];
    hotel.name = [hotelDict objectForKey:@"name"];
    hotel.capacity = [hotelDict objectForKey:@"capacity"];
    [hotels addObject:hotel];
}

希望这有帮助。

编辑代码正确性

答案 1 :(得分:0)

您需要使您的对象符合NSCoding协议......这意味着,您需要实现两个方法(不要忘记将对象声明为

@interface Hotel : NSObject<NSCoding>{
   //your declarations here...
}

和实施

@implementation Hotel
////
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:Name forKey:someKeyRepresentingProperty];
    //and so one...
}

-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [self init];
    if(self){
        self.Name = [aDecoder decodeObjectForKey:someKeyRepresentingProperty];
        //and so one...
    }
    return self;
}

然后,您将能够非常轻松地存储和阅读您的对象。