这是我的第一篇文章,所以请对我友善和建设性。
我试图通过 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中写入的
在这里我尝试检索扩展中的数据
-
(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"];
似乎是空的,所以某处数据不流动。
我做错了什么??
任何类型的提示将不胜感激。