首先,我有一个管理 NSMutableArray 的类。当类被实例化时,它应该查看是否已经保存了一个数组并加载它,或者创建一个新数组。
每次添加项目时都应保存。但是:什么也没发生。
#import "NEList.h"
@interface NEList()
@end
@implementation NEList
@synthesize theInternArray;
-(id) initWithArray {
self = [super init];
if(self != nil) {
NSLog(@"build");
theInternArray = [[NSMutableArray alloc] initWithCapacity:20];
return self;
}
return nil;
}
-(id) initWithContent {
self = [super init];
if(self != nil) {
NSLog(@"load");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"theFiles"];
theInternArray = [NSMutableArray arrayWithContentsOfFile:filePath];
if(theInternArray == nil) {
theInternArray = [[NSMutableArray alloc] initWithCapacity:200];
}
NSLog(@"second %@", theInternArray);
return self;
}
return nil;
}
-(BOOL) save {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"theFiles"];
return [self.theInternArray writeToFile:filePath atomically:NO];
}
-(BOOL) addObject:(NEListItem *)theItem {
[theInternArray addObject:theItem]; [self save];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = theItem.theBestBeforeDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [theItem.theName stringByAppendingString:@" expires!"];
localNotif.alertAction = NSLocalizedString(@"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
return true;
}
-(NEListItem *) getElementAtIndex:(NSUInteger)theIndex {
return [theInternArray objectAtIndex:theIndex];
}
-(BOOL)removeObjectByName:(NSString *)theName {
for (NEListItem *tempItem in theInternArray) {
if([tempItem.theName isEqualToString:theName]) {
[theInternArray removeObject:tempItem];
break;
return true;
}
}
NSLog(@"Nicht gefunden");
return false;
}
@end
在另一个拥有 NEList 实例的类中调用 save 方法