How compare the user actual time with a NSArray? - objective-c

I have a NSArray with many different hours as NSStrings. My question is, how can I compare the actual time of the user with the values into the NSArray and get which is the next hour to the actual user? For example, if the NSArray has got #"07:00", #"07:30", #"08:00", and now it's 07:40, how can I achieve that the app returns 08:00 as the next hour?? Maybe with NSTimers??
I know it's hard to understand thus many thanks.

Lookup NSDate , after you've read that you might find NSDateComponents and NSDateFormatter useful. The rest is programming... If you get stuck ask another question giving the code you've produced and the problem you are having.
HTH

Related

Working with time intervals in data logging?

I'm programming a data logging application. I need to be able to store a time interval typed in by the user using Core Data. For instance, if the user completes a task in seven minutes and twenty-three seconds, he/she can type 7:28 into the NSTextField and that will be part of the data.
What class should I use to store the time? NSDate seems to be the right way of doing it, but it does not seem to store time intervals. I see that there is an NSTimeInterval class. However, with no particular reference for it, I do not know how to use it.
Also, when this time interval is stored in objects within Core Data, I need to be able to retrieve those items and sort them (using NSSortDescriptor); in order to retrieve the entry that logged the lowest time interval. This is just additional information to help figure out what I need to do here.
From the docs: NSDate objects represent a single point in time.
From your use case it sounds like you want the user to log a relative time, and then to be able to sort by which is the smallest. In that case, NSDate is not a good option. The best solution is to just store the time interval as an NSUInteger, where the integer represents your value in seconds, and then do the appropriate conversions on either end.
If the user types in 7:28, could you convert this into seconds (448 seconds) and store it in a NSUInteger? That would make sorting it easily because you would not have to deal with separate minute and second values.
Here's what I think you should do:
Have two fields for user input: one for minutes and one for seconds.
Have some code like this:
NSInteger totalTime1 = 0;
totalTime += [minuteField.text integerValue]*60;
totalTime += [secondField.text integerValue];
Now store totalTime1 using Core Data. To retrieve the times and sort them, do something like this:
//Retrive times
NSArray *retrievedTimes = [NSArray arrayWithObjects: time1FromCoreDataAsNSNumber, time2FromCoreDataAsNSNumber, etc, nil];
NSArray *sortedRetrievedTimes = [retrievedTimes sortedArrayUsingSelector:#selector(compare:)];
//Now the array is sorted from lowest to highest
NSInteger lowestValue = [[sortedRetrievedTimes objectAtIndex:0] integerValue];
Hope this helps!

converting day of week index to string objective c

currently, i am working on an app that uses Core Data. One of my managed objects has a property that keeps track of the day of week (Sunday - Saturday) as an integer (0-6). For the sake of sorting the objects by day as well as less overhead in saving, i definitely believe the best practice is to save the days as indexes and then convert to string during runtime. The question becomes the best practice to convert the index to its corresponding day as a string. ie. 0=>#"Sunday" and 6 => #"Saturday". I can obviously use NSCalendar and NSDate and NSDateComponents to achieve this. It just seems like a very roundabout way to go about it given the simplicity of the task. Naturally, a simple NSString array defined as such could do the trick:
NSString *dayOfWeek[7] = {#"Sunday",#"Monday",#"Tuesday",#"Wednesday",#"Thursday",#"Friday'"#"Saturday"};
But then i find myself constantly redefining this same variable over and over again. A global constant NSString could work. Another idea I had was creating a function that used this dayOfWeek array and then including it in the files that need it. What do you think. What's the best practice?
How about one of the weekdaySymbols methods of NSDateFormatter?
Another solution would be to define a category method on NSString, for example, to return the string based on the number. Then the strings array can be static and only used in that method.

Searching an NSArray o strings with an NSDate

Hard to get the headline correct since there is so much to tell.
I got this NSArray (A portion of it):
Mon, 06:00, Radioshow Morning, Mon, 10:00, Lunch radio, 14:00, Afternoon Radio and so on.
The NSArray is from an plist in the app.
What I need to build (and failed with) is a search function that shows me the right program with these search values:
searchDay and searchTime
Both those values are from NSDate.
I've been Googling for about and hour now and hasn't come up with anything usefull so my last hope stands to stackoverflow to show me what I am missing.
I've been dabbling with dateFromString, compare, timeIntervalSinceNow but for some reason failed to achive what I am about to do.
Greatful for any help givven.
TIA
Mattias
You should use an NSArray of NSDictionary objects instead of various object types in your NSArray:
NSDictionary *morningShow = [NSDictionary dictionaryWithObjectsAndKeys:#"Mon",#"day","10:00",#"time","morning",#"name",nil];
Then add that to your array. Then, when you are searching, you have a uniform data structure to search inside of.
I think I have solved it.
But I must say I am intrigued by phooze answer.
The way I am doing it now is reading the values (NSString) from the array converting them into an NSDate object and comparing those with timeIntervalSinceDate.
By that I can figure out if currentTime is between two times in the array and such I know what show is on. I've just come up with the solution, the base code is working but the whole code isn't done yet, just on paper/in my mind.
But it feels like a somewhat ugly code... lots of doing small things.
But I will pre sue this to the end and if it still looks inefficient and ugly I will look in to other solutions.

Add missing objects to create an ordered collection

The subject is vague because I'm not sure how to articulate in one sentence what I want.
Here goes:
I have an NSArray of NSDictionaries. Each NSDictionary represents one day of the calendar year. Each NSDictionary has a key "date" with a value of NSDate. There should be 365 NSDictionary items in the array. The dictionary is created by a server that I don't control, and it sometimes is missing as many as 100 days.
I need to ensure the array has 365 dictionaries, each one day later than the next.
I currently sort the array by date, iterate through it, copying the NSDictionaries from the current array to a new array. While so doing, I compare the current Dictionary's date value with the date value for the next dictionary. If there is more than one day between the two dates, I add enough new dictionaries to the new array to cover those missing days (and set their dates accordingly), then continue through.
Since the dates are supposed to ordered, I wonder if there is not already a mechanism in the framework or language that I can use to say "Here is an array, and this keypath is supposed to be consecutive. Find and create the elements that are missing, and here's a block or method you can use to initialize them".
Something about my method just feels poorly implemented, so I turn to you. Thoughts?
Thanks.
The way you did it sounds perfectly sane, and there is nothing to my knowledge that will do it automatically in the base framework.
This code will sort them.
NSArray *dates; // wherever you get this...
NSArray *sortedDates = [dates sortedArrayUsingComparator:^(id obj1, id obj2)
{
return [[obj1 valueForKey:#"date"] compare:[obj2 valueForKey:#"date"]];
}];
As for creating the missing entries, you'll have to do that yourself.
You don't need to do the sort:
Create an array with 365 (or 366) placeholder dictionaries (you can possibly use the same one for all slots, or use NSNull)
iterate through the passed in array and figure out which day each of the dictionaries is for. Place each dictionary in its rightful slot in your array.

Comparing dates in Cocoa

hi i want to know how to get current date?
i want to compare current date with a date i m fetching from a plist files using following code.
NSDate *expDate = [licenseDictionary objectForKey:#"Expires"];
for comparison i m using the following code
if([curDate compare:expDate] == NSOrderedAscending )
but its not working. can anybody help me.
In the interest of teaching someone how to fish rather than just feeding him:
Have a look at the Date and Time Programming Guide.. The Programming Guides in the documentation are your first stop when trying to understand a topic. They provide an overview of what can be done and contain useful example code.
These guides also have links to the documentation of the specific classes that are used. In this case there is the NSDate Class Reference which has sections on creating dates and comparing dates.
Edit
To answer you comment about this not working, I think the problem could be that you haven't created the object that you've stored in the dictionary as an NSDate. Again. Have a look at the creating dates documentation. It will be something like
NSDate *expiryDate = [NSDate dateWithNaturalLanguageString:#"31/01/10"];
But this is just an example, there are other ways of setting a date string.
To get the current date, simply use:
NSDate * today = [NSDate date];
To compare to another date:
if ([today compare:expirationDate] == NSOrderedAscending)
{
// today's date is before the expiration date
}