2014-08-30 62 views
-1

我有自定义类。我想添加到类型为NSDictionary的类属性,该属性将通过给定标签返回此类的属性。但我做不到。有没有可能?我有错误:用自定义类对象创建字典

[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]' 

CODE:

@interface Car : NSObject 
@property (nonatomic, strong) NSNumber *topic; 
@property (nonatomic, strong) NSNumber *car; 
@property (nonatomic, strong) NSDictionary *variables; 
@end 

@implementation Car 
- (NSDictionary *)variables 
{ 
return @{ 
     @"781" : _topic, 
     @"782" : _car, 
}}; 
@end 
+2

你可能会考虑将'variables'设为只读属性,或者更好,只是一个普通的旧方法。 – jlehr 2014-08-30 21:24:37

+0

@jlehr虽然我同意,[这个答案](http://stackoverflow.com/a/10758831/2792531y)似乎表明它可能并不重要。 – nhgrif 2014-08-30 21:33:16

回答

3

你得到这个错误,因为你正试图插入nil(可能未初始化/未分配的对象)到无法完成的Objective-C集合。如果您需要在Objective-C集合中代表nil,则需要使用[NSNull null]


根据你添加的代码,问题是你还没有初始化你的变量。

有一个问题,在其他地方,你需要在某些时候的东西(?也许在init)来初始化这些,但可以肯定,误差不会再次发生,你可以这样做:

- (NSDictionary *)variables { 
    return @{ 
     @"781" : _topic ?: [NSNull null], 
     @"782" : _car ?: [NSNull null], 
    } 
}; 
+0

看,我添加一些代码 – 2014-08-30 21:18:50

+0

@avfvadfvfnvadlfjnvadlf我更新了我的答案。 – nhgrif 2014-08-30 21:22:49

+0

nhgrif,谢谢,我该如何返回这个类的实例变量_topic的值? – 2014-08-30 21:24:46

相关问题