簡體   English   中英

ios - 將NSArray轉換為NSDictionary

[英]ios - convert NSArray to NSDictionary

我想將nsarray轉換為我正在使用的nsdictionary

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
    id objectInstance;
    NSUInteger indexKey = 0;

    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
    for (objectInstance in array)
        [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];

    return (NSDictionary *)[mutableDictionary autorelease];
}

輸出結果是:

{
    0 =     {
        Event = "";
        ID = 1;    };
    3 =     {
        Event = "";
        ID = 77;    };
    2 =     {
        Event = "";
        ID = 23;    };
    1 =     {
        Event = "";
        ID = 45;    };
    7 =     {
        Event = "";
        ID = 10;    };
    5 =     {
        Event = "";
        ID = 26;    };
    6 =     {
Event = "";
        ID = 27;
    };
    8 =     {
Event = "";
        ID = 28;
    };
}

轉換為nsdictionary后,nsdictionary的順序不符合原始順序,我想在nsarray中顯示相同的順序,我不知道怎么做? 你能幫助我嗎?

NSDictionary沒有訂單。 對密鑰進行排序並使用它們來訪問條目。

如果我從評論中對@ACB和@Zaph的回復中正確理解,您需要執行以下操作:

維護一個集合,將整數鍵映射到按鍵排序的對象值。

如果我理解正確,數組就不能滿足您的需要,因為數組中的整數鍵不允許“漏洞”。 但是,您需要允許漏洞:在您的問題的輸出中,缺少4的鍵值對。 因此,字典對您很有吸引力。

不幸的是,正如@Zaph指出的那樣,字典不允許你維護它包含的鍵值對的排序。 但是,您說,您只想在UITableView按鍵排序的字典中顯示值。 據推測,只要字典的內容在表視圖中以正確的順序顯示,字典序列化到磁盤的順序(使用writeToFile:atomically:重要了。

字典可用於此目的如下。 首先,我們需要一個PFXKeyValuePair類;

@interface PFXKeyValuePair : NSObject
@property (nonatomic) id<NSCopying> key;
@property (nonatomic) id value;
+ (PFXKeyValuePair *)pairWithValue:(id)value forKey:(id<NSCopying>)key;
+ (NSArray *)pairsWithValues:(NSArray *)values forKeys:(NSArray *)keys;
@end

@implementation PFXKeyValuePair
+ (PFXKeyValuePair *)pairWithValue:(id)value forKey:(id<NSCopying>)key
{
    PFXKeyValuePair *pair = [[PFXKeyValuePair alloc] init];
    pair.value = value;
    pair.key = key;
    return pair;
}
+ (NSArray *)pairsWithValues:(NSArray *)values forKeys:(NSArray *)keys
{
    NSAssert(values.count == keys.count, @"The array of values must be the same size as the array of keys.");
    NSUInteger count = values.count;
    NSMutableArray *mutableRes = [NSMutableArray array];
    for (NSUInteger index = 0; index < count; index++) {
        PFXKeyValuePair *pair = [PFXKeyValuePair pairWithValue:values[index] forKey:keys[index]];
        [mutableRes addObject:pair];
    }
    return [mutableRes copy];
}
@end

其次,我們需要NSDictionary上的類別方法:

@interface NSDictionary (PFXAdditions)
- (NSArray *)pfx_keyValuePairsSortedByKeyUsingComparator:(NSComparator)comparator;
@end

@implementation NSDictionary (PFXAdditions)
- (NSArray *)pfx_keyValuePairsSortedByKeyUsingComparator:(NSComparator)comparator
{
    NSArray *sortedKeys = [self.allKeys sortedArrayUsingComparator:comparator];
    NSArray *sortedValues = [self objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
    return [PFXKeyValuePair pairsWithValues:sortedValues forKeys:sortedKeys];
}
@end

注意 :在上面, PFXpfx是占位符。 你應該用適合你項目的前綴替換它們。

然后我們可以使用這個類別方法來填充我們的UITableView 假設我們有一處房產

@property (nonatomic) NSDictionary *events;

我們假設表視圖只有一個部分,其中將顯示這些事件。

然后我們可以在我們的UITableViewController子類中實現–tableView:numberOfRowsInSection:如下:

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.events.count;
}

在我們的–tableView:numberOfRowsInSection:實現–tableView:numberOfRowsInSection:我們可以確定字典中的相應條目,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //...
    NSArray *pairs = [self.events pfx_keyValuePairsSortedByKeyUsingComparator:^(id obj1, id obj2) {
        NSNumber *key1 = (NSNumber *)obj1;
        NSNumber *key2 = (NSNumber *)obj2;
        return [key1 compare:key2];
    }];

    NSUInteger index = [indexPath indexAtPosition:1];
    PFXKeyValuePair *pair = pairs[index];
    /*
    At this point, pair.value will be a dictionary as in your output above 
    holding a value for the key @"Event" and a value for the key @"ID".
    */
    //...
}

通過使pairs成為屬性並且僅在必要時計算它(例如,僅在重新加載表的數據之前計算pairs ,可以更快地實現這一點。

注意 :使用這種方法,字典仍然不會被序列化到磁盤(當按順序調用-writeToDisk:atomically:時,您的輸出仍然與您的問題中的輸出相同。 但是,這並不重要:當在表視圖中向用戶顯示數據時,數據將按照您的希望進行排序。

這是示例之一,獲取emplyee列表NSMutableArray並創建NSMutableDictionary .......

NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:@"saman",@"Ruchira",@"Rukshan",@"ishan",@"Harsha",@"Ghihan",@"Lakmali",@"Dasuni", nil];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {

NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList  = [dict objectForKey:firstLetter];

if (!letterList) {
    letterList = [NSMutableArray array];
    [dict setObject:letterList forKey:firstLetter];
}

[letterList addObject:word];}NSLog(@"dic %@",dict);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM