编辑对象的值并复制它
我有一个事件对象,如下所示,
NSString *name;
NSString *date;
NSInteger id;
我将事件对象存储在 NSMutabelArray 中。我想添加日期并存储在不同的数组中。为此,我使用下面的代码
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 = newDate;
}
,因此在循环的最终迭代之后,deleg.events 中的所有对象都具有最后计算的日期。我该如何解决呢。 谢谢
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 = newDate;
}
So after final iteration of loop all the objects in deleg.events is having the last calculated date. How can I resolve it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有举办新活动。您的行
只是创建一个引用完全相同的事件对象的新变量,这意味着您现在已将完全相同的对象添加到数组中 5 次。
我不知道你的
Events
类是如何工作的。如果它符合 NSCopying,那么您可以使用如果不符合,则必须创建一个全新的
Events
对象(使用[[Events alloc] init]
或其他适合该类)并用适当的数据填充它。You're not making a new event. Your line
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 useIf 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.