Editing value of an Object and duplicating it
I have an events object which is given below
NSString *name;
NSString *date;
NSInteger id;
I am storing the events object in a NSMutabelArray. I want to add to the date and store in a different array. For that I am using the code below
NSString *curDate = event.Date;
NSDate *date = [dateFormat dateFromString:curDate];
for(int i=0;i<5;i++)
{
Events *newEvent = event;
NSDate *newDate = [date dateByAddingTimeInterval:60*60*24*1];
newEvent.date = [dateFormat stringFromDate:newDate];
[deleg.events addObject:newEvent];
date = ne开发者_Go百科wDate;
}
So after final iteration of loop all the objects in deleg.events is having the last calculated date. How can I resolve it. Thanks
You're not making a new event. Your line
Events *newEvent = event;
is just creating a new variable that references the exact same event object, which means you now have added the exact same object to the array 5 times.
I don't know how your Events
class works. If it conforms to NSCopying, then you can use
Events *newEvent = [[event copy] autorelease];
If not, you'll have to create a brand new Events
object (using [[Events alloc] init]
or whatever is appropriate for the class) and populate it with the appropriate data.
精彩评论