ios - 如何初始化从 NSString 到 NSArray 的字典

标签 ios iphone objective-c nsdictionary

我正在尝试创建一个从 NSString 到数组(不确定它应该是 NSArray 还是 NSMutableArray)。

属性:

@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 我意识到字典在构建后是空的。这里有什么问题,我该如何更改?

最佳答案

代码行之后

 if(! _categories) {

添加

_categories = [NSMutableDictionary new];

关于ios - 如何初始化从 NSString 到 NSArray 的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20224098/

相关文章:

ios - 带有 ARSCNView 的 UIViewController 在显示在屏幕上之前需要花费大量时间

ios - 检测点击 UITabBarController 中的选项卡

iphone - 用相同的方法更新 UILabel 两次

ios - iPhone X 上的现有应用程序 "scale"如何处理?

objective-c - 使用AVCaptureSession仅记录AUDIO

objective-c - 在 iOS 5 中,如何使用 AudioSession 确保音频通过扬声器播放,尽管耳机已插入?

iphone - MPMediaItem 到 AVAsset 到 .MP3

ios - vImage 与使用dispatch_apply 的普通循环具有相同的性能

iphone - 应用程序在后台时计划的 NSTimer?

ios - Objective-C 中的布局容器 - 它们存在吗?