Reputation: 147
I've been trying to store an NSDate object into an NSMutableArray and then retrieve it later (to get an elapsed time).
Here is what I tried, for mutable array initialization and storage:
in the .h file:
@property (nonatomic, strong) NSMutableArray *startTime;
in the implementation (.m) file:
@synthesize startTime = _startTime;
// init the mutable array - create some temporary elements as placeholders
NSDate *temp = [NSDate date];
for (int i = 0; i < 3; i++) {
[self.startTime addObject:temp];
}
Here's what's not working:
[self.startTime replaceObjectAtIndex:iurl withObject:[NSDate date]]; //iurl is an NSUInteger
NSDate *now = [self.startTime objectAtIndex:iurl];
NSLog(@"Now = %@", now);
All I wanted to do was a) store an NSDate object at an index (NSUInteger iurl here), and then b) retrieve and access that object. In the code above, now is always (null). How can I store an NSDate object into an array or mutable array so it may be retrieved later?
Upvotes: 0
Views: 1479
Reputation: 2185
You forgot to actually initialize your array, which is why its null.
Add in self.startTime = [NSMutableArray array];
before you initialize your date object.
This will initialize self.startTime as an empty array, which will allow you to add objects to it.
self.startTime = [NSMutableArray array];
NSDate *temp = [NSDate date];
// Now you can add temp to self.startTime
[self.startTime addObject:temp];
// Since temp is the only object in your array so far, its index is 0.
NSDate *now = [self.startTime objectAtIndex:0];
Upvotes: 2