簡體   English   中英

NSDictionary Objective-C

[英]NSDictionary Objective-C

我正在嘗試以字符串作為鍵以下列方式存儲數據,我希望將數組作為值。

關鍵對象

“letters”{'a','b','c','d'}
“數字”{1,2,3,4,5,6,7}

這是否可以在代碼中使用NSDictionary 如果是這樣,那會是什么樣子? 我真的很困惑。

在代碼中執行此操作的簡單方法(並且只是您可以執行此操作的多種方法之一):

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSArray arrayWithObjects:@"a", @"b", @"c", @"d", nil] forKey:@"letters"];
[dict setObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], nil] forKey:@"numbers"];

這創建了一個帶有字符串數組和NSNumber對象數組的NSDictionary ,還有其他方法可以創建數組,但這表明了一種基本的方法。

根據以下評論:

如果你想一次一個地添加項目到數組...

  // create the dictionary and add the letters and numbers mutable arrays
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  NSMutableArray *letters = [NSMutableArray array];
  NSMutableArray *numbers = [NSMutableArray array];
  [dict setObject:letters forKey:@"letters"];
  [dict setObject:numbers forKey:@"numbers"];

  // add a letter and add a number
  [[dict objectForKey:@"letters"] addObject:@"a"];
  [[dict objectForKey:@"numbers"] addObject:[NSNumber numberWithInt:1]];  
  // This now has an NSDictionary (hash) with two arrays, one of letters and one 
  // of numbers with the letter 'a' in the letters array and the number 1 in 
  // the numbers array

假設您有一個名為lettersNSArray和一個包含正確值的numbers

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
    letters, @"letters",
    numbers, @"numbers",
    nil
];

如果你想保持dict ,請確保retain ,或者使用allocinitWithObjectsAndKeys

有關更多詳細信息,請參閱NSDictionary API參考。

您可以將它們表示為屬性列表。 屬性列表文檔

<dict>
    <key>letters</key>
    <array>
        <string>a</string>
        <string>b</string>
        <string>c</string>
        <string>d</string>
    </array>
    <key>letters</key>
    <array>
        <integer>1</integer>
        <integer>2</integer>
        <integer>3</integer>
        <integer>4</integer>
        <integer>5</integer>
        <integer>6</integer>
        <integer>7</integer>
    </array>
 </dict>

有關如何在Cocoa中序列化和反序列化數據的概述,請參閱Cocoa的歸檔和序列化指南

暫無
暫無

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

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