2011-05-16 55 views
0

我有这样的代码: 我想一些瓦莱斯存储在一年中的一天,我设定期限,例如15/05/2011 20/05/2011到的iOS:更新一个NSMutableArray

在viewDidLoad中

: 我存储空值,那么我可以存储无处不在的值我想要在阵列中,我使用“定点值”:

appDelegate.years = [[NSMutableArray alloc] init]; 

for (int i = 0; i < 50; i++) // I set 50 years 
{ 
    [appDelegate.years insertObject:[NSNull null] atIndex:i]; 
} 

months = [[NSMutableArray alloc] init]; 
for (int i = 0; i < 12; i++) 
{ 
    [months insertObject:[NSNull null] atIndex:i]; 
} 

days = [[NSMutableArray alloc] init]; 
for (int i = 0; i < 31; i++) 
{ 
    [days insertObject:[NSNull null] atIndex:i]; 
} 

在我的方法:

int firstDay = 15; 
int lastDay = 20; 
int firstMonth = 4; 
int lastMonth = 4; 
NSString *string = first; //this is the value that I want to store in the period 


for (int i = firstMonth; i < lastMonth+1; i++) 
{ 

    for (int j = firstDay; j < lastDay+1; j++) 
    { 
     NSMutableArray *values = [[NSMutableArray alloc] init]; 
      [values addObject:string]; 
      [days replaceObjectAtIndex:j withObject: values]; 
      [values release]; 
    } 

    [months replaceObjectAtIndex:i withObject:days]; 

} 

[appDelegate.years replaceObjectAtIndex:0 withObject:months]; //0 is 2011 

OK,在这个代码我sto重新存储在我存储在数组“索引”中的一个数组“索引”中的数组“索引”中存储的数组“索引”中的一个数组“索引”中的数组“值”中的值,它工作正常;但在此之后,如果我想将另一个字符串存储在同一位置的数组值中?

例如:我有另一个NSString * string2 =“秒”,我想将这个字符串存储在同一天的位置,然后我想在同一天数组值与“第一”和“第二”,然后我可以' t do“[days replaceObjectAtIndex:j withObject:values];”但我能做什么呢?

回答

0

如果我推断这是正确的,你正试图在同一天存储第二个值,对吧?

如果没有特别的需要按照你现在的方式来布置你的数据结构,我会强烈建议你使用365天的普通数组。你目前所看到的结构与树结构相似,这也很好,但是用数组实现很痛苦(而且非常低效的内存)。

您似乎忘记了一旦您在树中的某个位置初始化了一个数组,您可以简单地追加到该现有数组。

说了这么多,下面是根据您目前的解决方案我的输入:

for (int i = firstMonth; i <= lastMonth; i++) 
{ 
    for (int j = firstDay; j <= lastDay; j++) // use <= instead of + 1, it's more intuitive 
    { 
     NSMutableArray* values = [days objectAtIndex:j]; 
     if (values == nil) 
     { 
      values = [[NSMutableArray alloc] init]; 
      [days insertObject:values atIndex:j]; 
     } 
     [values addObject:string]; 
     [values release]; 
    } 
    // This is unnecessary. days will never be something else than the current i-var days. 
    //[months replaceObjectAtIndex:i withObject:days]; 
} 
0

有两件事情,我觉得有问题的这种方法 -

  1. 您的日期迭代算法是错误的。它可以在同一个月的日期内正常工作,但如果你考虑15/4到20/5,那么并非所有的日期都会有价值。
  2. 您当前存储值的方式效率低下。怎么样一个NSMutableDictionary?当你迭代你的日期时,你检查日期是否存在(NSDate作为键可能不是个好主意,因为它们也有时间组件),如果它不存在,用当前值创建一个可变数组并将其设置为对象为日期。如果存在,获取可变数组并将当前值附加到它。通过这种方式,您可以快速检索日期的所有值,而不会使商店超出需要。

但是,如果你想以同样的方式进行,你需要做出一些改变 -

对于值部分,

if ([days objectAtIndex:j] == [NSNull null]) { 
    [days setObject:[NSMutableArray array] AtIndex:j]; 
} 
NSMutableArray *values = [days objectAtIndex:j]; 
[values addObject:string]; 

您还需要应对其他阵列与此类似。

相关问题