NSObject子类自定义方法导致NSInvalidArgumentException

时间:2014-05-16 04:41:28

标签: objective-c nsobject subclassing

我正在使用NSJSONSerialization获取一些JSON并将其解析为自定义NSObject子类。这很好用,我可以使用以下方法从中检索值:

CustomProperties* properties = [[CustomProperties alloc] init];
[properties objectForKey:@"nameOfKey"]

我的子类的简单实现:

CustomProperties.h

#import <Foundation/Foundation.h>

@interface CustomProperties : NSObject

- (id)objectForKey:(NSString *)key;

@end

CustomProperties.m

@implementation CustomProperties

-(id) init {
    if (self = [super init]) {
        /* do most of initialization */
    }
    return(self);
}

- (id)objectForKey:(NSString *)key
{
    return nil;
}

@end

问题

我正在尝试添加一个自定义实例方法,如果检索到的JSON值为nil,则可以使用默认值将检索到的值处理到float中。

我的想法很简单:

CustomProperties.h

@interface CustomProperties : NSObject

// ...existing id interface here
- (CGFloat)getFloatValueForKey:(NSString*)key defaultValue:(CGFloat)defaultValue;

@end

CustomProperties.m

@implementation CustomProperties

// ...existing id method here

- (CGFloat)getFloatValueForKey:(NSString*)key defaultValue:(CGFloat)defaultValue
{
    if (key == nil)
        return 0;

    if ([self objectForKey:key] == nil)
        return defaultValue;
    else
        return [[self objectForKey:key] floatValue];
}

@end

这样我就可以这样称呼它:

CustomProperties* properties = [[CustomProperties alloc] init];
[properties getFloatValueForKey:@"nameOfKey" defaultValue:0.2];

这当然会引起轰动:

-[__NSCFDictionary getFloatValueForKey:defaultValue:]: 
unrecognized selector sent to instance
'NSInvalidArgumentException', reason: '-[__NSCFDictionary getFloatValueForKey:defaultValue:]: 
unrecognized selector sent to instance 

我真的明白它没有正确实施,我错过了一些东西!只是不知道是什么。

修改

深入挖掘,看起来当它首次被初始化时(当我解析JSON时),它将其设置为__NSCFDictionary

CustomProperties* properties = [[CustomProperties alloc] init];
properties = [jsonNSDictionaryObjectInstance objectForKey:@"properties"];
customDetailsInstance.properties = properties;

1 个答案:

答案 0 :(得分:0)

我必须创建一个自定义initWithProperties方法,该方法捕获传入的NSCFDictionary并使用objectForKey解析属性。

解析JSON时:

// jsonNSDictionaryObjectInstance is actually an __NSCFDictionary
CustomProperties* properties = [[CustomProperties alloc] initinitWithProperties[initWithProperties objectForKey@"theJSONKeyYouAreParsing"]];
customDetailsInstance.properties = properties;

然后是CustomProperties类:

<强>·H

- (id)initWithProperties:(NSDictionary*)properties;

@property (nonatomic) CGFloat aCustomProperty;
@property (nonatomic) CGFloat anotherCustomProperty;

<强>的.m

-(id) initWithProperties:(NSDictionary*)properties
{
    if (self = [super init]) {
        /* do most of initialization */
        self.aCustomProperty = [[properties objectForKey:@"jsonSubKey"] floatValue];
        self.anotherCustomProperty = [[properties objectForKey:@"anotherJsonSubkey"] floatValue];
    }
    return(self);
}
相关问题