Reputation: 1248
I am trying to count how many screen captures a user made in my app. Unfortunately I am new to Objective C and really never worked with different type of Arrays or how to store things in them.
After a screen capture is made I want to call the method screenshotTaken in MLBookMarkDataProvider.m from my main.m class (where the screenshot got taken). I wanna store the int code in an Array that does not get cleared out after not using the method/class or app gets closed.
How shall I accomplish this ? I assume this is not rocket science for someone more experienced within C, all code examples is greatly appreciated. Regards!
main.h
int code;
……
main.m
- (void)viewDidLoad
{
………..
self.bookmarkDataProvider = [[MLBookmarkDataProvider alloc] initWithDelegate:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(screenshotTaken) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}
- (void) screenshotTaken
{
code ++;
[self.bookmarkDataProvider screenshotTaken:code];
}
MLBookmarkDataProvider.m
- (void) screenshotTaken : (int) code
{
// Some code here, the Array(NSUserDefaults) below gets cleared after closing main.m class or shutting down the app :(
NSNumber *number = [NSNumber numberWithInt:code];
[[NSUserDefaults standardUserDefaults] setObject:number forKey:@"ArrayNumber"];
if(Array has more then 5 items… blabla..){
NSLog(@"Print Array:%@",number);
// NSLog(@"code:%@",[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
}
Upvotes: 1
Views: 192
Reputation: 1314
I don't really know why you would use an array to accomplish such thing, i would just save an integer in NSUserDefualts like this.
-(void)increaseScreenshotCount{
//this will work even the first time when your key does not exist
//get the value from UserDefaults and increase it ++
NSInteger CurCount = 0 ;
CurCount += [[NSUserDefaults standardUserDefaults] integerForKey:@"ScreenShotCount"];
CurCount++;
[[NSUserDefaults standardUserDefaults] setInteger:CurCount forKey:@"ScreenShotCount"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"Current Screenshot Count %d", [[NSUserDefaults standardUserDefaults] integerForKey:@"ScreenShotCount"]);
}
Upvotes: 1
Reputation:
Better way to store value in app even you app get closed/shutdown. Please Use .plist file to store value and retrive value from .plist file. It will improve your app performance also without failing.
Upvotes: 0