Been searching for the answer to this for a while now and I think due to the nature of my array set up, I may be searching for the wrong answer!
I have a class which handles adding items to my array:
// Item.h
@interface Item : NSObject {
NSString *name;
NSNumber *seconds;
}
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSNumber *seconds;
- (id)initWithName:(NSString *)n seconds:(NSNumber *)sec;
@end
and…
//item.m
@implementation Item
@synthesize name, seconds;
- (id)initWithName:(NSString *)n seconds:(NSNumber *)sec {
self.name = n;
self.seconds = sec;
return self;
}
@end
So to add an item, I use
Item *item1 = [[Item alloc] initWithName:@"runnerA" seconds:[NSNumber numberWithInt:780]];
I have some code which allows a user to edit a textfield (runner name) and the time which is a UIdatepicker set to hours and minutes. In the save method, that’s working fine. It’s the UPDATE that I cannot get to work. I’ve tried alsorts! Here’s the code at the moment…
mainAppDelegate *appDelegate = (mainAppDelegate *)[[UIApplication sharedApplication] delegate];
Item *item = [[Item alloc] initWithName:inputName.text seconds:[NSNumber numberWithInt:secs]];
[appDelegate.arrItems replaceObjectAtIndex:rowBeingEdited withObject:item];
The above is simply adding a new item to the array (which is what I don’t want). I’m not sure how to replace values. At the function, I have the row I need to update (rowBeingEdited) and the fields inputName.text and secs are both OK. (NSLog out confirms this).
How do I use the replaceObjectAtIndex to actually replace it with the values?! It’s driving me mad now!!
Since you are simply trying to edit a particular row, why not use those property accessors that you already have set up in
Item? It would look something like this:An a side note, are you using garbage collection, or do you manually release the
Itemobjects that you create when adding items to the array? If you are doing it manually, it should look like this:This follows the rule of thumb: if you
alloc,copyorretainanything, you must alsoreleaseit. Note that this works because the array will retain the item when it is added.