2012-02-12 35 views
1

是否可以爲NSMutableArray設置標籤?我必須以某種方式在數組中確定需要重寫的單個數組,並且如果我只需將該內部數組的標記設置爲1(或其他數字),則這將非常容易。給NSMutableArray添加標籤

例子:

NSMutableArray* outerArray = [NSMutableArray new]; 

NSMutableArray* innerArray1 = [NSMutableArray new]; 
NSMutableArray* innerArray2 = [NSMutableArray new]; 
NSMutableArray* innerArray3 = [NSMutableArray new]; 
NSMutableArray* innerArray4 = [NSMutableArray new]; 

[outerArray addObject:innerArray1]; 
[outerArray addObject:innerArray2]; 
[outerArray addObject:innerArray3]; 
[outerArray addObject:innerArray4]; 

//now let's say innerArray1 needs to be rewritten 
//I would like to be able to do this 

[innerArray1 setTag:100]; 

//then later, when I need to determine which of the arrays inside outerArray 
//needs to be rewritten, I can just do this 

for(NSMutableArray* temp in outerArray) { 
    if(temp.tag == 100) { 
     //do what I need to do 
    } 
} 

但你不能用NSMutableArrays使用setTag:。什麼是解決方法?

回答

2

數組是有序的集合,所以你爲什麼不跟蹤哪些索引需要重寫。

當某些事情發生時,需要編寫外部數組索引爲0(在您的示例中爲innerArray1)的數組時,緩存索引0 - 作爲屬性,如果此例程需要跨越單獨的方法。

然後,當需要重寫時,請參考緩存索引。檢索要重寫的數組,如下所示:NSArray *arrayToRewrite = [outerArray objectAtIndex:cachedIndexToRewrite];或直接訪問它:[[outerArray objectAtIndex:cachedIndexToRewrite] replaceObjectAtIndex:whatever withObject:whatever];

+1

或者,由於數組嵌套,nsindexpath可能會更合適 – 2012-02-12 04:32:32

+0

這看起來很有希望,我想我可能忽略了這個簡單的解決方案。也許我只是需要睡覺。 – 2012-02-12 04:33:57

+0

@Chris:我甚至都不知道有這麼漂亮的東西。 – Wienke 2012-02-12 15:21:05

2

您可以改爲使用NSMutableDictionary。 「標籤」只是關​​鍵,數組就是價值。

+0

這不完全是我的問題。問題是我想能夠確定哪些數組在我的數組中,需要重寫。我需要一種方法來動態標記單個數組進行重寫。 – 2012-02-12 03:23:26

-1

使你的內部數組類變量。然後你可以訪問它們:

for(NSMutableArray* temp in outerArray) { 
if(temp == self.innerArray1) { 
    //do what I need to do 
} 
+0

我不能這樣做,因爲數組將要從不同的視圖控制器和類訪問。 – 2012-02-12 04:32:16

+0

啊,沒有意識到這一點。不要以爲這是在原始問題中提到的。 – Keller 2012-02-13 17:27:32

1

使用關聯的對象。你甚至可以添加一個類別到NSMutableArray,它會爲它們添加一個tag屬性。

@interface NSMutableArray (TagExtension) 
@property (nonatomic, assign) NSInteger tag; 
@end 

@implementation NSMutableArray (TagExtension) 
@dynamic tag; 
static char TagExtensionKey; 
-(NSInteger)tag { 
    NSNumber *ourTag = (NSNumber *)objc_getAssociatedObject(self, &TagExtensionKey); 
    if(ourTag) { 
     return([ourTag integerValue]); 
    } 

    return(0); 
} 

-(void)setTag:(NSInteger)newTag { 
    objc_setAssociatedObject(self, &TagExtensionKey, [NSNumber numberWithInteger:newTag], OBJC_ASSOCIATION_RETAIN); 
} 
@end 

參見:How to add properties to NSMutableArray via category extension?

+0

我不知道你可以添加類別屬性 - 我會看看這個。 – 2012-02-12 04:30:51

+0

請注意,必須導入'ObjectiveC.runtime'。 '#import '。 – 2016-02-16 13:02:54

1

不知道爲什麼一本字典是這裏的壞主意......作爲替代方案,您可以:

  1. 記得指數
  2. ,或者如果每個條目一個獨特的陣列,你可以簡單地用指針來引用它:

    NSArray * tagged = theArray;

    for (NSMutableArray * at in outerArray) { 
        if (tagged == at) { 
        //do what I need to do 
        } 
    }