2013-11-26 75 views
0

試圖創建一個字典(不知道是否應該NSDictionaryNSMutableDictionary)從NSString到一個數組(不知道是否應該NSArrayNSMutableArray)。我如何初始化從NSString的字典來的NSArray

屬性:

@property(nonatomic, readonly) NSMutableDictionary * categories; 

實現:

@synthesize categories = _categories; 


- (NSMutableDictionary *)categories{ 
    if(! _categories) { 
     for(PFObject * each in self.products) { 
      NSString * currentcategory = [each valueForKey:@"subtitle"]; 
      NSArray * currentlist = [_categories objectForKey:currentcategory]; 
      if(! currentlist) { 
       currentlist = [[NSArray alloc] init]; 
      } 
      NSMutableArray * newArray = [currentlist mutableCopy]; 
      [newArray addObject:each]; 
      NSArray * newlist = [NSArray arrayWithArray:newArray]; 
      [_categories setObject:newlist forKey:currentcategory]; 
     } 
    } 
    NSLog(@"After constructor the value of the dictionary is %d", [_categories count]); 
    return _categories; 
} 

從調試NSLog我意識到是字典的施工後空。這裏出了什麼問題,我該如何改變它?

回答

6

後的代碼行

if(! _categories) { 

添加

_categories = [NSMutableDictionary new]; 
+0

哎呀。謝謝! – Ra1nWarden

0

如果您沒有在代碼的某個地方初始化數組_category然後。 必須將它實例裏面

if(!_categories) 

你的NSMutableArray _categories實例未分配和初始化呢。

要創建的NSMutableArray實例只是增加

_categories = [NSMutableArray arrayWithCapacity:0];