views:

24

answers:

2

Is this ok?

NSDate *myDate;

Because I used something like this before:

NSDate *myDate = [[NSDate alloc] init];

if (something)
     myDate = thisDate;
else
     myDate = thatDate;

[myFunction initWithDate:myDate];

I always got "Value stored to 'myDate' during its initialization is never read". If I do something like this

if (something)
     NSDate *myDate = thisDate;
else
     NSDate *myDate = thatDate;

[myFunction initWithDate:myDate];

I get "Unused variable 'myDate'" and "'myDate' undeclared (first use in this function)"

How does the release look like? Autorelease?

A: 

your first try was close

NSDate *myDate;

if (something)
     myDate = thisDate;
else
     myDate = thatDate;

[myFunction initWithDate:myDate];

First line declares an NSDate variable named myDate. Then you run your test and set the value of myDate appropriately.

kubi
That's it, thanks. Sorry can't mark both answers as solution.
testing
A: 

If you just want to point to a pre-existing date, you could do something like this:

NSDate *myDate = something ? thisDate : thatDate;
[myFunction initWithDate:myDate];

or even

[myFunction initWithDate:something ? thisDate : thatDate];

However, to more clearly answer your question, yes, this could should be fine:

NSDate *myDate;

if (something) {
    myDate = thisDate;
} else {
    myDate = thatDate;
}

You can also initialize myDate to nil (myDate = nil), if you want.

As far as memory management goes, you're just setting a pointer -- you're not creating a new object, or taking ownership (via retain) of an existing object -- so you don't need to use release or autorelease at all.

mipadi
That is what I wanted to know. If thisDate or thatDate is released myDate is pointing to nowhere. So I depend on the them. I think they are created by convenience functions (dateFromComponents/dateByAddingTimeInterval returns new NSDate objects), so I hope they are autoreleased. Nothing to do with the memory management here?
testing
If you're only using the pointer `myDate` inside of a method, it doesn't really matter. If `myDate` is an instance or static variable, then you should `retain` `thisDate` or `thatDate`. If they are created from a convenience method, they should be autoreleased already, unless the method documentation says otherwise.
mipadi