Check to see if NSDate holds a date or is empty - iphone

What would be the best way to see if an NSDate is actually set to a date or is empty? Returning its description or changing it to string returns "(null)"...?
Thanks.

If you want to see if an instance of NSDate (or any object) is nil, just compare it to nil. A non-null NSDate object will never be empty; it always contains a date. Both -init and +date return an NSDate object initialized to the current date and time, and there is no other way to create an instance of this class.
if(someData == nil) {
// do stuff
}

if it doesn't hold a date, then you have a nil pointer, so simply
if (!date) {
...
}
or more explicitly
if (date == nil) {
...
}

Related

NSCalendar.startOfDayForDate(date:) equivalent for iOS 7 with non-optional return type

Is it possible to change an NSDate object so that the result is equivalent to NSCalendar.startOfDayForDate(date:)? That method is only available to iOS 8 and newer, but I am looking for something that works on iOS 7.
I have looked at two methods:
NSCalendar.dateFromComponents(comps:) as described here: NSDate beginning of day and end of day. For instance, like this:
class func startOfDay(date: NSDate, calendar: NSCalendar) -> NSDate {
if #available(iOS 8, *) {
return calendar.startOfDayForDate(date)
} else {
let dateComponents = calendar.components([.Year, .Month, .Day], fromDate: date)
return calendar.dateFromComponents(dateComponents)!
}
}
NSDateFormatter.dateFromString(string:) by way of
stringFromDate(date:), i.e. converting the NSDate object into a string without the time, then converting it back into an NSDate object.
The problem with both methods is that they return an optional NSDate. I am reluctant to unwrap this implicitly and I’d rather avoid changing the return type of the method within which these methods are called.
I think the calendar.components() method returns an optional, because you can theoretically enter components that do not create valid date, like 2000-02-30. If, as in your case, the components already come from a valid date, I would not be reluctant to implicitly unwrap the optional.

In Swift what exactly is the difference between a function that returns a value and one that does not?

Here is some code that I am using in my program
func getDate() {
getTimeRightNow()
date = timeRightNow
sendDate()
print("date was sent")
}
func getTimeRightNow() {
timeRightNow = NSDate().timeIntervalSince1970
}
The function getDate() calls getTimeRightNow() which then gets the current NSDate and sets it equal to a variable timeRightNow. I then take timeRightNow and set date equal to it which I then pass along for further use.
Below, I have a second version. This time I instead have the getTimeRightNow() function return a value of type Double...
func getDate() {
date = getTimeRightNow()
sendDate()
print("date was sent")
}
func getTimeRightNow()-> Double {
timeRightNow = NSDate().timeIntervalSince1970
return timeRightNow
}
Both versions seems to work exactly the same. I guess the second version lets me type one less line, is that the only advantage that it offers? Is the second version considered "best practice"? In the second version, is there any chance that the sendDate() function gets called BEFORE the getTimeRightNow() function finishes and sets a value for date? How about in the first version, is there any chance that timeRightNow gets set equal to date BEFORE the getTimeRightNow() function finishes and sets a proper NSDate for timeRightNow?
Having trouble understanding this, appreciate the help
The difference between the function that has a return value and one that does not is that it returns a value. That can be really practical.
let aDate = myRandomDate()
let anotherDate = myRandomDate()
You would not be able to do this with a function that does not return a value.

Using customized setter/getter and initializing the property for a swift date

I have a class called Trip which has an NSDate property called date. My desire is to make sure that the date property always has the time value set to the beginning of the day. I do this by:
Creating an NSCalendar constant called calendar so that I can use the startOfDayForDate method to reset the date value.
Creating a custom setter method for the date property that calls the startOfDayForDate method.
However, I want to initialize the date property to the start of today's date.
The code that I have so far is shown below.
class Trip {
private let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date: NSDate {
get {
return self.date
}
set {
self.date = calendar.startOfDayForDate(newValue)
}
}
}
This code a) doesn't initialize the date property and b) (I discovered) results in an infinite loop when the setter is called. Upon further research, I believe that customized getters/setters are strictly computed, right?
How do I accomplish what I mentioned earlier:
a.) making sure that sets to the date property reset to the start of the day and
b.) initializing the date property to the start of today's date?
I think you want to have a date that will always be the start of the date. Replace your current date variable with this:
private var privateDate = NSDate()
var date: NSDate {
get {
return privateDate
}
set {
privateDate = calendar.startOfDayForDate(newValue)
}
}
There may be a slightly better way to do this, but I'm guessing your application won't have tens of thousands of your Trip class, so you should be fine.

Swift: Why class method has return type AnyObject?

NSDate.distantFuture() is documented to return an object of type NSDate.
So then, why does it have a return type of AnyObject, instead of NSDate?
In Objective-C distantFuture returns an id, not NSDate. Automatic Swift conversion makes this an AnyObject. When the class will be reviewed by Apple they will probably switch that to NSDate.
NSDate's distantFuture is actually from the distant past (at least Mac OS X 10.0, probably even before that). At this time many factory methods returned id because there was no instancetype. It was just to make it easier to call a subclasses method on the returned object.
This is actually documented as returning AnyObject.
returns nil if an event specified in the event mask does not happen before the specified date.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/clm/NSDate/distantFuture**
distantFuture
Creates and returns an NSDate object representing a date in the distant future.
Declaration
SWIFT
class func distantFuture() -> AnyObject
OBJECTIVE-C
+ (id)distantFuture
Return Value
An NSDate object representing a date in the distant future (in terms of centuries).
Discussion
You can pass this value when an NSDate object is required to have the date argument essentially ignored. For example, the NSWindow method nextEventMatchingMask:untilDate:inMode:dequeue: returns nil if an event specified in the event mask does not happen before the specified date. You can use the object returned by distantFuture as the date argument to wait indefinitely for the event to occur.
myEvent = [myWindow nextEventMatchingMask:myEventMask
untilDate:[NSDate distantFuture]
inMode:NSDefaultRunLoopMode
dequeue:YES];
Import Statement
import Foundation
Availability
Available in OS X v10.0 and later.

NSString or NSCFString in xcode?

I m taking a NSMutabledictionary object in NSString like this :
NSString *state=[d valueForKey:#"State"];
Now sometimes state may be null and sometimes filled with text.So Im comparing it.While comparing state becomes NSString sometimes and NSCFString othertimes..So unable to get the desired result..
if([state isEqualToString#""])
{
//do something
}
else
{
//do something
}
So while comparing it is returning nil sometimes.So immediately jumping into the else block.
I need a standard way to compare if the state is empty whether it is a NSString or NSCFString ...
How can I do it?
If you're unable to get the result you want, I can assure you it's not because you get a NSCFString instead of a NSString.
In Objective-C, the framework is filled with cluster classes; that is, you see a class in the documentation, and in fact, it's just an interface. The framework has instead its own implementations of these classes. For instance, as you noted, the NSString class is often represented by the NSCFString class instead; and there are a few others, like NSConstantString and NSPathStore2, that are in fact subclasses of NSString, and that will behave just like you expect.
Your issue, from what I see...
Now sometimes state may be null and sometimes filled with text.
... is that in Objective-C, it's legal to call a method on nil. (Nil is the Objective-C concept of null in other languages like C# and Java.) However, when you do, the return value is always zeroed; so if you string is nil, any equality comparison to it made with a method will return NO, even if you compare against nil. And even then, please note that an empty string is not the same thing as nil, since nil can be seen as the absence of anything. An empty string doesn't have characters, but hey, at least it's there. nil means there's nothing.
So instead of using a method to compare state to an empty string, you probably need to check that state is not nil, using simple pointer equality.
if(state == nil)
{
//do something
}
else
{
//do something
}
You can do this
if([state isEqualToString:#""])
{
//do something
}
else
{
//do something
}
You must have to type cast it to get the correct answer.
NSString *state = (NSString *) [d valueForKey:#"State"];
if(state != nil)
{
if(state.length > 0)
{
//string contains characters
}
}