2013-10-30 49 views
1

**有人能幫我理解這種類型的初始化嗎?這在我看來,這部分代碼:如何使用for循環創建和填充下面的結構? ObjectiveC

"username: @"Johny"樣子關鍵的NSDictionary initializationa對象**

NSArray *items = @[@{@"username": @"Johny", 
        @"userpic": @"Photo.png", 
        @"image": @"photo1.jpg"}, 

        @{@"username": @"George", 
        @"userpic": @"Photo.png", 
        @"image": @"photo2.jpg"}, 

        @{@"username": @"Mandy", 
        @"userpic": @"Photo.png", 
        @"image": @"photo3.jpg"}, 

        @{@"username": @"Jacob", 
        @"userpic": @"Photo.png", 
        @"image": @"photo4.jpg"}, 

        @{@"username": @"Brandon", 
        @"userpic": @"Photo.png", 
        @"image": @"photo5.jpg"}, 

        @{@"username": @"Dave", 
        @"userpic": @"Photo.png", 
        @"image": @"photo6.jpg"} 
        ]; 

*在我的代碼我得到的所有值通過使用循環 *

for (NSDictionary *dictionary in items) { 
{ 
    // 

} 

回答

0

蘋果公司在2012年WWDC發佈Objective-C時發生了一些變化。如果您還沒有看過WWDC 2012視頻Modern Objective-C,那麼我強烈建議您查看解釋所引入更改的視頻。當中添加這些變化是Array LiteralsDictionary Literals

基本上就像你可以通過創建創建String Literal如下:

NSString *name = @"Slim Shady" 

蘋果推出Array LiteralsDictionary Literals過以下示例是視頻

哪裏開始創建陣列的選項如下:

NSArray *myArray; 
myArray = [NSArray array]; // an empty Array 
myArray = [NSArray arrayWithObject:anObject]; // an array with a single object 
myArray = [NSArray arrayWithObjects: a, b, n, nil]; // array with 3 objects a, b, c 

數組文本,您可以通過以下方式創建磁盤陣列:

myArray = @[ ]; // an empty Array 
myArray = @[anObject]; // array with a single object 
myArray = @[a, b, c]; // array with 3 objects a, b, c 

,你可以看到使用字面更直觀,更容易創建數組。同樣,對於NSDictionary 當最初創建詞典的選擇是:

NSDictionary *myDict; 
myDict = [NSDictionary dictionary]; // empty Dcitionary 
myDict = [NSDictionary dictionaryWithObject:object forKey:key]; 
myDict = [NSDictionary dictionaryWithObjectsAndKeys: object1, key1, object2, key2, nil]; 

字典字面允許您創建字典在以下幾個方面:

myDict = @{ }; // empty ditionary 
myDict = @{ key:object }; // notice the order of the key first -> key : object 
myDict = @{ key1:object1 , key2:object2 }; 
2

這是一個使用新(ish)Objective-C literals syntax字典對象的數組。

除了傳統的文本字符串,這是我們都知道,愛:@"Hello World",主要有:

  • NSArray文字:@[ element1, element2 ],它具有不需要尾nil[NSArray arrayWithObjects:]做的優勢。
  • NSDictionary文字:@{ key : value, key : value },與[NSDictionary dictionaryWithObjects:forKeys:]相比,其優勢在於鍵值順序更自然。
  • NSNumber文字:@(YES)(布爾值),@(1.2)(浮點數),@(123)(整數)。

他們都有更簡潔和自然的優勢。

0

在iOS 6中,Apple創建了一個初始化NSArray的新方法,這就是這種情況。

它的功能就像arrayWithObjects函數一樣,只是語法稍有不同。

您的NSArray充滿了NSDictionary對象。