这是我的第一篇文章,所以请与我保持友好和建设性。
我试图通过NSuserDefauls与我的Today Extension共享一组自定义对象。
我知道我不能在NSUserdefaults中放置自定义对象,所以我用NSKeyedArchiver编写了它们 - NSKeyedUnarchiver来在NSData中对它们进行转换。
这是我的自定义类
#import "Counter.h"
@implementation Counter
@dynamic city;
@dynamic address;
@dynamic event;
@dynamic date;
@dynamic time;
@dynamic counter;
@dynamic latitude;
@dynamic longitude;
- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:self.city forKey:@"city"];
[encoder encodeObject:self.address forKey:@"address"];
[encoder encodeObject:self.event forKey:@"event"];
[encoder encodeObject:self.date forKey:@"date"];
[encoder encodeObject:self.time forKey:@"time"];
[encoder encodeObject:self.counter forKey:@"counter"];
[encoder encodeObject:self.latitude forKey:@"latitude"];
[encoder encodeObject:self.longitude forKey:@"longitude"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
self.city = [decoder decodeObjectForKey:@"city"];
self.address = [decoder decodeObjectForKey:@"address"];
self.event = [decoder decodeObjectForKey:@"event"];
self.date = [decoder decodeObjectForKey:@"date"];
self.time = [decoder decodeObjectForKey:@"time"];
self.counter = [decoder decodeObjectForKey:@"counter"];
self.latitude = [decoder decodeObjectForKey:@"latitude"];
self.longitude = [decoder decodeObjectForKey:@"longitude"] ;
}
return self;
}
@end
这是应用程序内的编码功能。
- (void)saveInUserDefault {
//Counter is my Custom class
//I'm Using MagicalRecord
NSArray *array = [Counter MR_findAllSortedBy:@"date" ascending:NO];
NSMutableArray *defaultMutableArray = [NSMutableArray arrayWithCapacity:array.count];
NSUserDefaults *defaultArray = [[NSUserDefaults alloc] initWithSuiteName:@"group.LorenzoLoRe.Everycount"];
for (Counter *cnt in array) {
NSData *dataToDefault = [NSKeyedArchiver archivedDataWithRootObject:cnt];
[defaultMutableArray addObject:dataToDefault];
}
[defaultArray setObject:defaultMutableArray forKey:@"counts"];
[defaultArray synchronize];
}
此时查看日志,数据似乎是在NSUserDefaults中写的
在这里,我尝试在Extension
中检索数据-
(void)takeLastCounts {
NSUserDefaults *defaultArray = [[NSUserDefaults alloc] initWithSuiteName:@"group.company.product"];
[defaultArray synchronize];
NSArray *dummyArray = [defaultArray arrayForKey:@"counts"];;
NSMutableArray *arrayFromDefault= NULL;
Counter *cter = nil;
for (NSData *data in dummyArray) {
cter = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[arrayFromDefault addObject:cter];
}
self.cnt_1 = arrayFromDefault[0];
self.cnt_2 = arrayFromDefault[1];
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
self.eventLabel.text = self.cnt_1.event;
self.dateLabel.text = [formatter stringFromDate:self.cnt_1.date];
self.counterLabel.text = self.cnt_1.counter.stringValue;
self.timeLabel.text = self.cnt_1.time;
}
当我尝试执行扩展时,没有错误,只有空数组。
特别是NSArray *dummyArray = [defaultArray arrayForKey:@"counts"];
似乎是空的,所以某些地方的数据不会流动。
我做错了什么?
任何形式的提示都将受到赞赏。