在NSUserDefault中将自定义对象存储在NSMutableArray中我最近一直在尝试将我的iPhone应用程序的搜索结果存储在NSUserDefaults集合中。我还使用它成功地保存了用户注册信息,但出于某种原因,试图存储我的自定义位置类的NSMutableArray始终是空的。在本文中,我尝试将NSMutableArray转换为NSData元素,但得到了相同的结果(是否可以在iPhone上使用NSUserDefault保存整数数组?)我尝试过的代码示例如下:保留:[prefs setObject:results forKey:@"lastResults"];[prefs synchronize];或NSData *data = [NSData dataWithBytes:&results length:sizeof(results)];[prefs setObject:data forKey:@"lastResults"];或NSData *data = [NSKeyedArchiver archivedDataWithRootObject:results];[prefs setObject:data forKey:@"lastResults"];负载:lastResults = (NSMutableArray *)[prefs objectForKey:@"lastResults"];或NSData *data = [prefs objectForKey:@"lastResults"];memcpy(&lastResults, data.bytes, data.length);或NSData *data = [prefs objectForKey:@"lastResults"];lastResults = [NSKeyedUnarchiver unarchiveObjectWithData:data];在以下建议之后,我还在我的对象中实现了NSCoder(忽略对NSString临时的过度使用):#import "Location.h"@implementation Location@synthesize locationId;@synthesize companyName;@synthesize addressLine1;
@synthesize addressLine2;@synthesize city;@synthesize postcode;@synthesize telephoneNumber;@synthesize description;
@synthesize rating;@synthesize priceGuide;@synthesize latitude;@synthesize longitude;@synthesize userLatitude;
@synthesize userLongitude;@synthesize searchType;@synthesize searchId;
@synthesize distance;@synthesize applicationProviderId;@synthesize contentProviderId;- (id) initWithCoder: (NSCoder *)coder{
if (self = [super init])
{
self.locationId = [coder decodeObjectForKey:@"locationId"];
self.companyName = [coder decodeObjectForKey:@"companyName"];
self.addressLine1 = [coder decodeObjectForKey:@"addressLine1"];
self.addressLine2 = [coder decodeObjectForKey:@"addressLine2"];
self.city = [coder decodeObjectForKey:@"city"];
self.postcode = [coder decodeObjectForKey:@"postcode"];
self.telephoneNumber = [coder decodeObjectForKey:@"telephoneNumber"];
self.description = [coder decodeObjectForKey:@"description"];
3 回答
RISEBY
TA贡献1856条经验 获得超5个赞
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults]; NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"savedArray"];if (dataRepresentingSavedArray != nil){ NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray]; if (oldSavedArray != nil) objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray]; else objectArray = [[NSMutableArray alloc] init];}
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:objectArray] forKey:@"savedArray"];
- (void)encodeWithCoder:(NSCoder *)coder;{ [coder encodeObject:label forKey:@"label"]; [coder encodeInteger:numberID forKey:@"numberID"];}- (id)initWithCoder:(NSCoder *)coder;{ self = [super init]; if (self != nil) { label = [[coder decodeObjectForKey:@"label"] retain]; numberID = [[coder decodeIntegerForKey:@"numberID"] retain]; } return self;}
森栏
TA贡献1810条经验 获得超5个赞
lastResults = [prefs arrayForKey:@"lastResults"];
- 3 回答
- 0 关注
- 527 浏览
添加回答
举报
0/150
提交
取消