开发者

Objective-C : Changing "self" value inside self

I have a category on NSDate, and I want to implement some functions to manipulate the date, like :

NSDate *thedate = [NSDate date];
[thedate setToMidnight];

so I have a function in NSDate like :

-(void)setToMidnight {
   some code with calendars and comps

   self = theNewDate;
}

This works inside the function, but outside this member function, thedate has not changed. I开发者_StackOverflow中文版 understand this malfunction because I've been told that self is just a local variable created inside the member function. So, how can I make this work ?

Of course, I could have written :

thedate = [thedate dateAsMidnightDate]
or thedate = [NSDate dateAtMidnightFromDate:thedate]

but I feel it has more sense inside the instance class, as I don't want to change the date but just adjust some values of the previously created one.


You can't. Specifically:

  1. A function or method cannot modify local variables in the calling context.

  2. NSDate is not mutable (i.e. you can't modify an NSDate once it's created).

Therefore, no such method can be written. The closest you can get would be a class that wraps an NSDate and forwards messages to that internal NSDate object, which reassigns the date instance variable when you want to make it represent a new date.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜