How do I use the alarm every Monday? - nsdate

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];
NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
[nowComponents setWeekday:2]; //Monday
[nowComponents setWeek: [nowComponents week] + 1]; //Next week
[nowComponents setHour:8]; //8a.m.
[nowComponents setMinute:0];
[nowComponents setSecond:0];
NSDate *timeDate = [gregorian dateFromComponents:nowComponents];
localNotif.fireDate = timeDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatInterval = NSWeekdayCalendarUnit;
localNotif.alertBody = [NSString stringWithFormat:#"nowtime %# == %# %# %# %# ",date,saveDataWeekday,saveDataAmPm,saveDataHour,saveDataMinute];
localNotif.alertAction = #"info";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
Alarm does not work on a specified day of the week
I want to setting
for example
-> Every monday or Every friday or Every day

Related

How can summarize all numbers in NSArray?

I have NSArray with strings - 00:02:34, 02:05:17 so i need to calculate all strings in my array and get result: 2 hours:7 minutes and 51 seconds.
I tried this:
// Get strings from array for the first and separate for three objects by:
for (NSDictionary *dic in dicts) {
NSString *string = dic[#"duration"]; (my type of string 00:00:00)
NSArray *components = [string componentsSeparatedByString:#":"];
NSInteger minutes = [components[1] integerValue];
NSInteger seconds = [components[2] integerValue];
NSInteger hour = [components[0] integerValue];
}
But how can i summ this date to get results? Thanks for help.
There are a few different ways you could approach this.
Personally, I'd iterate through dicts and convert each duration string to seconds and keep count of the total seconds in an integer outside of the loop.
Then, you can easily convert the cumulative seconds total back into hours, minutes and seconds and compose a string from them, after the loop is complete:
int totalSeconds = 0;
for (NSDictionary * dic in dicts) {
NSString *string = dic[#"duration"];
NSArray *components = [string componentsSeparatedByString:#":"];
totalSeconds += (int) [components[0] integerValue] * 60 * 60;
totalSeconds += (int) [components[1] integerValue] * 60;
totalSeconds += (int) [components[2] integerValue];
}
int hour = totalSeconds / 3600;
int mins = (totalSeconds % 3600) / 60;
int secs = totalSeconds % 60;
NSString * totalString = [NSString stringWithFormat:#"%d:%d:%d", hour, mins, secs];
Note: you'll have to write a bit of code to compose the string and include zeros as appropriate, where any of the values are less than 10.

Difference between output NSDate from NSDateFormatter and NSDateComponents

let stringWithDate = "2015-07-16T6:08:32.000Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let dateComponents = NSDateComponents()
dateComponents.year = 2015
dateComponents.month = 7
dateComponents.day = 16
dateComponents.hour = 6
dateComponents.minute = 8
dateComponents.second = 32
let dateFromDateFormatter = dateFormatter.dateFromString(stringWithDate) //"Jul 16, 2015, 8:08 AM"
let dateFromDateComponents = NSCalendar.currentCalendar().dateFromComponents(dateComponents)! //"Jul 16, 2015, 6:08 AM"
dateFromDateFormatter == dateFromDateComponents //false
Why these dates are not the same?
After some digging, I have found a solution:
NSDateFormatter includes information about NSTimeZone (Z at the end of Sting) while NSDateComponents doesn't. So we need to simple inform dateComponents about NSTimeZone:
dateComponents.timeZone = NSTimeZone(abbreviation: "UTC")
The output dates are now the same.
Adding the same information to dateFormatter:
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
doesn't change anything, because there is information about NSTimeZone yet.

Iphone - How do you sort an NSMutableArray into ascending order?

In Xcode i am trying to make a graph into which some points (X,Y) are given by the user.The user can choose how many points he or she wants to plot on the graph. I have stored the X axis points in an NSMutableArray and the Y axis points in an NSMutableArray but now i need to sort these into ascending order so i can fix a bug with the graph when having two points with the same x or y axis plot. The NSMutableArrays contains primitive int's. An example of what i need to do is if i am given 4 coordinates for one of the axis such as 4,8,5,3 i need the array to be sorted into 3,4,5,8
The code below doesn't include the graph generation because it is quite long
Thanks for the help! -
int userInputCount;
printf("How many coordinates would you like to plot? ");
scanf("%i", &userInputCount);
printf("\n");
NSMutableArray * xCoordArray = [[NSMutableArray alloc] init];
NSMutableArray * yCoordArray = [[NSMutableArray alloc] init];
for (int i = 1; i <= userInputCount; i++){
int xCoord;
int yCoord;
printf("(%i) Enter coordinates [X,Y]: ", i);
scanf("%i,%i", &xCoord, &yCoord);
NSNumber *xCoordinate = [[NSNumber alloc] initWithInt:xCoord];
NSNumber *yCoordinate = [[NSNumber alloc] initWithInt:yCoord];
[xCoordArray addObject:xCoordinate];
[yCoordArray addObject:yCoordinate];
}
After working on it for a while I figured it out if anybody is trying the same thing
for (int j = 0; j < 2; j++){
for (int i = 0; i < [yCoordArray count] - 1; i++){
int yExchangeIntOne = [[yCoordArray objectAtIndex:i] intValue];
int yExchangeIntTwo = [[yCoordArray objectAtIndex:i +1] intValue];
if (yExchangeIntOne > yExchangeIntTwo){
[yCoordArray exchangeObjectAtIndex:i+1 withObjectAtIndex:i];
i = 0;
}
int xExchangeIntOne = [[xCoordArray objectAtIndex:i] intValue];
int xExchangeIntTwo = [[xCoordArray objectAtIndex:i +1] intValue];
if (xExchangeIntOne > xExchangeIntTwo){
[xCoordArray exchangeObjectAtIndex:i+1 withObjectAtIndex:i];
i = 0;
}
}
}
This goes right after the
[xCoordArray addObject:xCoordinate]; and the
[yCoordArray addObject:yCoordinate]; in the loop

NSFetchRequest with fetchOffset doesn't return expected results

I've encountered something strange when trying to get "paged" entities from Core Data.
Here is the code I use for fetching:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"User"
inManagedObjectContext:self.managedObjectContext];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"userIdentifier beginswith[cd] %# AND selected == 1",userIdentifier];
fetchRequest.fetchOffset = offset;
fetchRequest.fetchLimit = limit;
[fetchRequest setEntity:entity];
NSLog(#"offset %d limit %d",fetchRequest.fetchOffset,fetchRequest.fetchLimit);
NSError *requestError = nil;
NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest
error:&requestError];
NSLog(#"fetched items count = %d",items.count);
And here are the logs:
2013-01-31 16:01:28.127 offset 0 limit 100
2013-01-31 16:01:28.128 fetched items count = 6
2013-01-31 16:01:40.533 offset 1 limit 100
2013-01-31 16:01:40.535 fetched items count = 5
2013-01-31 16:01:53.029 offset 2 limit 100
2013-01-31 16:01:53.032 fetched items count = 4
2013-01-31 16:01:55.468 offset 3 limit 100
2013-01-31 16:01:55.470 fetched items count = 3
2013-01-31 16:02:00.776 offset 4 limit 100
2013-01-31 16:02:00.779 fetched items count = 2
2013-01-31 16:02:02.325 offset 5 limit 100
2013-01-31 16:02:02.328 fetched items count = 1
2013-01-31 16:02:03.837 offset 6 limit 100
2013-01-31 16:02:03.839 fetched items count = 0
2013-01-31 16:02:07.714 offset 6 limit 100
2013-01-31 16:02:07.717 fetched items count = 0
For this test I had 6 entries for "User".
What am I doing wrong?
Thanks
Your logs indicate that everything is working as expected.
Congratulations!
Found the problem:
fetchRequest.fetchOffset = offset*limit;

Split a string at case change

Given a string say "acbXyzKlm" i want to split it to abc, Xyz,Klm. One naive way to do this is to go traverse the string and detect the case change to split. I was wondering if there is a better algorithm for this.
To determine if a point in the string is a valid breaking point, you need to have read both characters around breaking point. So any algorithm to solve this will need to analyze the case of every character.
Your algorithm does just that, hence it's computationally optimal. Any "better" algorithm would be a variant and/or micro-optimization of that, with the same overall complexity.
I needed this today, so I implemented it with a category:
#interface NSString (Extensions)
- (NSString*) spacify;
#end
#implementation NSString (Extensions)
- (NSString*) spacify
{
// ignore irrelevant strings
if (self.length < 1)
return self;
NSMutableString* result = [NSMutableString stringWithString:self];
// create a range starting after the first character
NSRange range;
range.location = 1;
range.length = [self length] - 1;
// match any uppercase character
NSRegularExpression* r = [NSRegularExpression regularExpressionWithPattern: #"[A-Z]"
options: 0
error: nil];
// replace matches with the match preceded by a space
[r replaceMatchesInString: result
options: 0
range: range
withTemplate: #" $0"];
return [NSString stringWithString:result];
}
#end
Tests:
#implementation NSStringExtensionsTest
- (void) testSpacify
{
NSString* target = #"ThisIsAStringX";
NSString* expected = #"This Is A String X";
NSString* actual = [target spacify];
STAssertEqualObjects(expected, actual, nil);
}
- (void) testSpacify_NoMatches_DoesNothing
{
NSString* target = #"thisisstring";
NSString* actual = [target spacify];
STAssertEqualObjects(target, actual, nil);
}
- (void) testSpacify_EmptyString_DoesNothing
{
NSString* target = #"";
NSString* actual = [target spacify];
STAssertEqualObjects(target, actual, nil);
}
- (void) testSpacify_InvalidLength_DoesNothing
{
NSString* target = #"A";
NSString* actual = [target spacify];
STAssertEqualObjects(target, actual, nil);
}
#end

Resources