在NSUserDefault中將自定義對象存儲在NSMutableArray中我最近一直在嘗試將我的iPhone應(yīng)用程序的搜索結(jié)果存儲在NSUserDefaults集合中。我還使用它成功地保存了用戶注冊信息,但出于某種原因,試圖存儲我的自定義位置類的NSMutableArray始終是空的。在本文中,我嘗試將NSMutableArray轉(zhuǎn)換為NSData元素,但得到了相同的結(jié)果(是否可以在iPhone上使用NSUserDefault保存整數(shù)數(shù)組?)我嘗試過的代碼示例如下:保留:[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"];負(fù)載: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];在以下建議之后,我還在我的對象中實(shí)現(xiàn)了NSCoder(忽略對NSString臨時(shí)的過度使用):#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"];
在NSUserDefault中將自定義對象存儲在NSMutableArray中
慕尼黑8549860
2019-08-03 14:03:27