Global NSDate variable seems to make app crash - uitableview

I have a global variable in FirstViewController.h
extern NSString *dateString;
it records the date/time of when I press saveText button. There is another button called readText which pushes a UITableView. The first cell on this table will print the date saved.
However, this only works if I first press the saveText button. Otherwise, if I just press readText, it crashes. How can I get it so that if there is no current datetime saved, that it doesn't crash?
Here is where I wrote the timestamp for saveButton:
-(IBAction)saveText:(id)sender{
//code to save text, irrelevant to the question//
dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterShortStyle];
NSLog(#"%#",dateString);
}
and here is the code to load the tableviewcells with the timestamp
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *str = #"Text- saved on: ";
str = [str stringByAppendingString: dateString];
self.list = [[NSArray alloc] initWithObjects: str, nil];
}

In my methods that use the variable dateString,
I used:
if([dateString length] == 0){
//perform standard procedure
}
else {
//what I want it to do
}

Related

How to show Single date in multiple events reload in MBCalendarKit

I am using a Calendar view in my project. I am using a MBCalendarKit. That time single date in single event show. But I want single date on multiple events show. But how it possible please help.
- (void) viewWillAppear: (BOOL)animated{
NSArray *title = [_caldevice valueForKey:#"pill"];
// NSLog(#"event name fetch %#",title);
NSArray *date =[_caldevice valueForKey:#"datetaken"];
// NSLog(#"event fetch %#",date);
NSArray*dose= [_caldevice valueForKey:#"dose"];
NSString *title1;
NSString*title2;
NSDate *date1;
NSData *imgdata;
CKCalendarEvent *releaseUpdatedCalendarKit;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd-MM-yyyy";
for (int i = 0; i < [date count]; i++){
title1 = NSLocalizedString(title[i], #"");
title2 = NSLocalizedString(dose[i], #"");
NSString *combined = [NSString stringWithFormat:#"%# - %#", title1, title2];
date1 = [dateFormatter dateFromString:date[i]];
releaseUpdatedCalendarKit = [CKCalendarEvent eventWithTitle:combined andDate:date1 andInfo:Nil];
// NSLog(#"Event: %# , %#",combined,date1);
// releaseUpdatedCalendarKit = [CKCalendarEvent eventWithTitle:combined andDate:date1 andInfo:Nil andColor:[UIColor blueColor]];
self.data[date1] = #[releaseUpdatedCalendarKit];
}
}
You're looping over a bunch of events and for each event, you're *replacing the previously assigned array with a new one, containing a single element.
Replace this:
self.data[date1] = #[releaseUpdatedCalendarKit];
with something more like this:
// 1. First, get the previous events for that day.
NSMutableArray <CKCalendarEvent *> *events = self.data[date1].mutableCopy;
// 2. If events exist, append the event, otherwise create an empty array with the new event.
if (events) {
[events addObject: newEvent];
}
else {
events = #[newEvent];
}
// 3. Set the events for the date key.
self.data[date1] = events;
This way you're doing an "add or create" operation, instead of overwriting each time.
Disclosure: I wrote and maintain MBCalendarKit.

how to add the button clicks and count in a dictionary

I have a method called addbuttonClicktocounter. When the function is called it should add the button name as key and number of clicks as count. I made this in my static library. When the user called these method again and again it should capture all the button names and number of clicks in one dictionary. If same button clicks again and again means the button name should remain same and the click count oly get increased. Here is my code what my tried upto my level:
NSMutableDictionary *BtnclicDict;
-(void) addButtonClickToCounter : (NSString*)button_Name button_click :(int)but_Click{
if([[BtnclicDict allKeys] containsObject:button_Name]){
int saveClick = [[BtnclicDict valueForKey:button_Name] integerValue];
but_Click = saveClick + but_Click;
NSNumber *click = [NSNumber numberWithInt:but_Click];
NSString *clickString = [click stringValue];
[BtnclicDict setObject:clickString forKey:button_Name];
NSLog(#"same button...,%#",click);
NSLog(#"same key dict...,%#",BtnclicDict);
} else {
NSString *but_Name = [NSString stringWithString:button_Name];
// NSLog(#"%#",but_Name);
NSNumber *click = [NSNumber numberWithInt:but_Click];
// NSLog(#"%#",click);
NSString *clickString = [click stringValue];
// BtnclicDict = [NSMutableDictionary dictionaryWithObject:but_Name forKey:click];
// BtnclicDict = [[NSMutableDictionary alloc]init];
[BtnclicDict setObject:clickString forKey:but_Name];
NSLog(#"working,%#",BtnclicDict);
// NSLog(#"%# Button Values...",BtnclicDict);
}
}
If you call this method from another class again and again it should collect all the details and make it into one dictionary.
You can try this.
-(void) addButtonClickToCounter : (NSString*)button_Name button_click :(int)but_Click{
if ([BtnclicDict valueForKey:buttonName])
but_Click += [[BtnclicDict valueForKey:button_Name] integerValue];
[BtnclicDict setValue:but_Click forKey:button_Name];
}

UIButton Title not updating all the time

I am programmatically changing the title of a UIButton to display count of items in a NSMutableArray.
Sometimes, the title does not update as I add items to the array. When I do the NSLog of what the title should be, it is correct but the button title does not update all the time.
Can anyone spot a problem with my code?
- (void) refreshAfterBlueToothScan
{
/*************************************Refresh Displayed Total********************/
//[_manualBCtemporaryCartArray26 removeAllObjects];
//_manualBCtemporaryCartArray26 = [[NSMutableArray alloc] init];
[localTempArray removeAllObjects];
if (!localTempArray)
{
localTempArray = [[NSMutableArray alloc] init];
}
// Get the DBAccess object;
DBAccess *dbAccess1 = [[DBAccess alloc] init];
// Get the products array from the database
//Get the latest NSMutableArray
localTempArray = [dbAccess1 getProductsFromTmpSales];
// Close the database because we are finished with it
[dbAccess1 closeDatabase];
//Count How many products in array
int iNumberofArrayProducts;
iNumberofArrayProducts = [localTempArray count];
NSString* productCount = [NSString stringWithFormat:#"%i", iNumberofArrayProducts];
NSLog(#"The NUMBER OF TmpTable PRODUCTS is %#",productCount);
//Sum the selling price of the records in the _manualBCtemporaryCartArray26
amountSum = [localTempArray valueForKeyPath:#"#sum.lTotalSellingPrice"];
NSLog(#"The total TmpTable SELLING PRICE is %#",amountSum);
NSNumberFormatter * formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
[formatter setMinimumFractionDigits:2]; // Set this if you need 2 digits
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithFloat:[amountSum floatValue]]];
NSLog(#"FORMATTED MONTHLY SALES IS,R%#",newString);
//This is a hack that replaces the comma with a dot. I want to display the Price as R2 000.10
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"/:,"];
newString=[[newString componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #"."];
NSString *item = [NSString stringWithFormat:#"R%# (%i)",newString, iNumberofArrayProducts];
/**********Play audio to warn user that item was added to cart*******/
// ivar
SystemSoundID mBeep;
// Create the sound ID
NSString* path = [[NSBundle mainBundle]
pathForResource:#"scanBarCode" ofType:#"mp3"];
NSURL* url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &mBeep);
// Play the sound
AudioServicesPlaySystemSound(mBeep);
// Dispose of the sound
//AudioServicesDisposeSystemSoundID(mBeep);
/**********END - Play audio to warn user that item was added to cart*******/
//When user scans the barcode, we want to display the product that was just scanned. This allows user to see what product they just scanned as it is automatically loaded on the shopping cart. Put IF Statement so this code only executes after the scanning barcode.
[self.searchDisplayController setActive: YES animated: YES];
//self.searchDisplayController.searchBar.hidden = NO;
self.searchDisplayController.searchBar.text = [NSString stringWithFormat:#"%i",fklInventoryID];
[self.searchDisplayController.searchBar becomeFirstResponder];
[self.searchDisplayController.searchBar resignFirstResponder];
NSLog(#"BUTTON ITEM IS,%#",item);
[manualTotalPriceBtn setTitle: item forState: UIControlStateNormal];
/*************************************END - Refresh Displayed Total********************/
}
Try this:
[manualTotalPriceBtn setAttributedTitle:nil forState:UIControlStateNormal];
[manualTotalPriceBtn setTitle:item forState:UIControlStateNormal];
If you are using a xib file the IB will set your value for the attributedTitle instead of the title.
try changing button type from system to custom.
Check that you update the button on the mainthread. If your method is called from a callback of whatever bluetooth scanner module you are using, it might be happening on a backround thread. This will cause button to sometimes update, sometimes it will not, or later.
If not, check the superview property of the button to not be nil. Maybe somewhere in your code you create a bew button, add it to the superview but forgot update your property to point to it (or some other scenario where you update a button that is not inserted in the view).

error in using date picker

the application crashed when calling this function, how ever in iPhone it works fine , but in iPad the application crashes and say
note: i'm using ActionSheetDatePicker library
Thread 1: EXC_BAD_ACCESS (cod = 1 , address = 0x9e...)
when i debug i found selectedDate is nil in iPad , but works fine in iPhone
#pragma mark - Implementation
- (void)dateWasSelected:(NSDate *)selectedDate element:(id)element {
// self.selectedDate = selectedDate;
//may have originated from textField or barButtonItem, use an IBOutlet instead of element
//DATE TEXT FIELD HERE
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd"];
//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
NSString *stringFromDate = [formatter stringFromDate:selectedDate];
self.textFieldBirthDate.text = stringFromDate ;
birthDate = stringFromDate ;
//"YYYY-MM-DD" the birthdate format
}
The git hub code which you provided is working fine for me and I did debug the code.
When user Taps on done button (After selecting the date) below code will be executed.
- (void)notifyTarget:(id)target didSucceedWithAction:(SEL)action origin:(id)origin {
if ([target respondsToSelector:action])
objc_msgSend(target, action, self.selectedDate, origin);
else
NSAssert(NO, #"Invalid target/action ( %s / %s ) combination used for ActionSheetPicker", object_getClassName(target), (char *)action);
}
Now here make sure you are getting value for self.selectedDate , if you are not getting then please do check that you are getting a breakpoint to below code when you just select a date by scrolling.
- (void)eventForDatePicker:(id)sender {
if (!sender || ![sender isKindOfClass:[UIDatePicker class]])
return;
UIDatePicker *datePicker = (UIDatePicker *)sender;
self.selectedDate = datePicker.date;
}
These codes are present in file
ActionSheetDatePicker.m
If you are getting the breakpoint here then make sure you are saving the date .Once you do check this the problem will be resolved.
Regards,
Anil

Numbers arent formatting with Decimal style

So i have an app which should format the value string in a SecondviewController to display on the firstViewController tab.
When a user enters numbers, its suppose to format it using a comma every 3 digits. But somehow i cant seem to get how to display it onto the firstViewController. Here is my code:
In secondViewController.m
-(IBAction) button:(id)sender{
NSString *string1 = self.addDigitField.text;
/* format the entered digits */
NSNumberFormatter *format = [NSNumberFormatter new];
[format setNumberStyle: NSNumberFormatterDecimalStyle];
NSNumber *n = [format numberFromString: addDigitField];
/* display the string1 value to the firstViewController Label*/
self.string1 = [self. addDigitField text]
FirstViewcontroller *first = self.tabBarController.viewControllers[0];
first.fvcString = self.string1;
}
now firstViewController.m
/* display the value into firstViewController label *
-(void) viewDidAppear:(BOOL) animated {
If (self.svcString != nil)
self.displayValue.text = self.svcString;
}
So my problem is, where in this code do i put the the message method to format the
Number ? The code i am trying to add is as follow :
[format stringFromNumber: n];
I typically use this way when doing it all on a single view app:
self.label.text = [format stringFromNumber: n];
And it formats it. But in my case of formatting the string to a firstViewcontroller
From the secondViewcontroller is where i am lost, any suggestion where i am going
Wrong ??
In your second view controller, replace
first.svcString = self.string1;
with
first.svcString = [format stringFromNumber:n];
The problem is in this line below :-
self.string1 = [self. addDigitField text];
In this your are setting the text value which is the previous value. You need to set the NSNumber value which you have converted using number formatter. Try like this
NSNumber *n = [format numberFromString:
addDigitField];
self.string1 = [format stringFromNumber:n];
FirstViewcontroller *first =
self.tabBarController.viewControllers[0];
first.fvcString = self.string1;
Now in your first view controller just replace the below line
self.displayValue.text = self.fvcString;

Resources