2011-05-16 53 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]; 

您還需要應對其他陣列與此類似。

相關問題