0

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?

3
  • What exception is thrown? My guess is iurl isn't an integer, which is the only valid index for arrays, but giving us the exception should pinpoint the issue. Commented Sep 13, 2012 at 0:51
  • Alternatively, your array hasn't been initialised with objects yet, so there's nothing at index iurl to replace. You can deal with this by adding null objects ([NSNull null]) to pad it out, but if you have to do this I'd have to question why you're using an array to begin with. Commented Sep 13, 2012 at 1:00
  • -arrayWithCapacity: returns an autoreleased object. Are you retaining it anywhere? Because if not, it's probably getting destroyed. Commented Sep 13, 2012 at 1:21

1 Answer 1

2

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.