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

我通过在我的数据模型中硬编码一些静态数据(酒店信息)来开始我的应用程序,以便在我的应用程序的任何地方都可以访问它们。 直到列表开始增长(仍然是静态数据),情况良好。 我试图找出如何通过使用plist来重新创build硬编码数据。 似乎挺直,但似乎无法弄清楚。

我的“酒店”对象标题:

@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”对象由我的DataModelpipe理。 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部分。 我想用plistreplace这个相同的信息。 如何读取plist文件来为每个键(名称,容量等)分配信息?

一旦你创build了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]; } 

希望这可以帮助。

编辑为代码正确性

你需要使你的对象符合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; } 

那么你将能够很容易地存储和读取你的对象。