Chr*_*oph 3 iphone core-data objective-c
我的一个实体上有一个可转换的属性,称为提醒.这是一个UILocalNotification.
现在,因为我想在添加它时安排它,并在删除时取消它,我想覆盖访问器来处理调度和取消.
那怎么样?
谢谢!
您实际上是在持久化UILocalNotification还是将其用作瞬态属性?
我不会存储它,而是将UILocalNotification存储userInfo为属性.您可以在该字典的键/值对中包含有关拥有实体的信息.例如:
您可以notificationID在userInfo字典中为键创建值,并将notificationIDCore Data实体上的属性设置为相同的值.这样,您只需要存储int或NSString存储在商店中(这比可转换的更好).
当您想再次获取UILocalNotification时,您可以在您的实体类上创建一个访问器,例如:
- (void)createNotification
{
static NSUInteger kDeadlineWarningPeriod = 3600;
UILocalNotification *notification = [[UILocalNotification alloc] init];
…
self.notificationID = @"some generated ID";
[notification.userInfo setValue:self.notificationID forKey:@"notificationID"];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[notification release];
}
- (void)cancelNotification
{
// We search for the notification.
// The entity's ID will be stored in the notification's user info.
[[[UIApplication sharedApplication] scheduledLocalNotifications] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UILocalNotification *notification = (UILocalNotification *)obj;
NSDictionary *userInfo = notification.userInfo;
NSString *notificationID = [userInfo valueForKey:@"notificationID"];
if ([notificationID isEqualToString:self.notificationID])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
*stop = YES;
self.notificationID = nil;
}
}];
}
Run Code Online (Sandbox Code Playgroud)
当然,如果您确实需要访问通知对象,则可以以相同的方式为通知创建访问器.
希望能帮助到你.
UPDATE
所以,既然你有一个属性,你可以调用提醒你的实体(我猜这是一个BOOL),它看起来像这样:
// .h
@property (nonatomic, assign) BOOL reminder;
// .m
- (void)setReminder:(BOOL)reminder {
[self willAccessValueForKey@"reminder"];
BOOL hasReminder = [[self primitiveValueForKey:@"reminder"] booleanValue];
[self didAccessValueForKey:@"reminder"];
if (hasReminder && !reminder) {
[self cancelNotification];
}
else if (!hasReminder && reminder) {
[self createNotification];
}
if (reminder != hasReminder)
{
[self willChangeValueForKey:@"reminder"];
[self setPrimitiveValue:[NSNumber numberWithBool:reminder] forKey@"reminder"];
[self didChangeValueForKey:@"reminder"];
}
}
Run Code Online (Sandbox Code Playgroud)
实际上,您根本不需要存储"提醒"属性,只需检查notificationID属性是否为零即可.这是我之前提出的建议.
我没有检查上面的代码,但我在两个项目中做了类似的事情.
请记住,如果您创建超过64个本地通知,则可能会遇到麻烦,因为您只能为每个应用创建多个通知.所以你可能想要在创建任何新的之前跟踪你有多少.
| 归档时间: |
|
| 查看次数: |
1619 次 |
| 最近记录: |