NSString and NSDictionary valueForKey - nil?



如果从字典中的空键/值获取数据,如何将默认值放入字符串中。

所以[myObject setMyString:[dictionary valueForKey:@"myKey"]];

所以如果我做了NSString *newString = myObject.myString,我会得到一个unrecognized selector error

同样,如果键值为空,我只需要一种插入默认字符串的方法;

如果dictionaryNSDictionary,您可能应该使用objectForKey,因为valueForKey用于KVC。它适用于NSDictionary,但如果密钥与某些NSDictionary KVC密钥冲突,例如"@allKeys"或"@count",则可能会咬到您。

我认为最短的可能是:

[dictionary objectForkey:@"myKey"] ?: @"defaultValue"

如果出于某种原因不想使用条件,有一种可怕的方法可以滥用现有的字典方法来生成get-by键或返回默认值。。。

[[dictionary objectsForKeys:[NSArray arrayWithObject:@"myKey"]
             notFoundMarker:@"defaultValue"]
 objectAtIndex:0]

你没有从我那里听到:(

这个怎么样?

NSString *value = [dictionary valueForKey:@"myKey"];
if (!value) value = @"defaultValue";
[myObject setMyString:value];

对一般情况使用[NSNull null],并在返回时进行处理。

在你的问题中,你不会得到"未被识别的选择器";newString将被设置为nil(而不是[NSNull null],所以我怀疑您可能有其他意思——也许是如何设置NSUserDefaults的默认值?

我用一个简单的NSDictionary扩展完成了这项工作。

NSDictionary+NSDictionaryExtensions.h

#import <Foundation/Foundation.h>
@interface NSDictionary (NSDictionaryExtensions)
- (id)objectForKey:(id)aKey defaultObject: (id) defObj;
@end

NSDictionary+NSDictionaryExtensions.m

#import "NSDictionary+NSDictionaryExtensions.h"
@implementation NSDictionary (NSDictionaryExtensions)
- (id)objectForKey:(id)aKey defaultObject: (id) defObj
{
    id ret = [self objectForKey: aKey];
    if ( ret == nil )
        return defObj;
    else
        return ret;
}
@end

然后我可以访问如下:

NSString* str = [dict objectForKey: @"a_key" defaultObject: @"default"];

尝试

if ( myObject == nil ) {
   [myObject setMyString:@""];
}

if ( [dictionary valueForKey:@"myKey"] == nil ) {
    [dictionary setObject:@"" forKey:@"myKey"];
}

无论您为字符串指定了什么默认值,它都不会使myObject.myString返回"无法识别的选择器错误"-通常属性myString要么存在,要么不存在("通常"是因为您可以深入Objective-C运行时的内部并玩游戏,但这很少(如果有的话(是您想要做的!(

你想干什么?如果您的目标是在未设置的myObject.myString上引发异常,那么您可以在属性实现中执行此操作。

例如,如果没有为给定的密钥设置值,valueForKey;将返回nil,因此您可以在属性中检查该值

- (void) setMyString:(NSString *)value
{  myString = value;
}
- (NSString *) myString
{
   if (myString == nil)
      @throw [NSException exceptionWithName:@"UnrecognizedSelector" reason:@"No value set for myString" userInfo:nil];
   return myString;
}

注:

  1. 在终端键入的代码,可能包含打字错误

  2. 代码假定垃圾收集/ARC打开,如果不需要,则需要添加适当的保留/复制/释放

但你真的想抛出一个例外吗?通常只有当字符串应该设置为时才会这样做,而不设置是异常条件-您不会抛出默认值。

根据@Paul Lynch,您必须检查除nil之外的[NSNull-null]。还建议检查您要查找的数据类型:

- (id) objectForKey: (id) key withDefault: (id) defaultValue
{
    id value = self[key];
    if (value == nil || [value isEqual: [NSNull null]] || ![defaultValue isKindOfClass: [value class]])
    {
        value = defaultValue;
    }
    return value;
}

您可以手动检查不同类型的nil值,如下所示:

extension NSDictionary {
func convertToString() -> String {
    let jsonData = try! JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData!
    if jsonData  == nil{
        return "{}"
    }else {
        return String(data: jsonData as! Data, encoding: String.Encoding.utf8)!
    }
}
func object_forKeyWithValidationForClass_Int(aKey: String) -> Int {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return Int()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return Int()
        }
    } else {
        // KEY NOT FOUND
        return Int()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return Int()
    }
    else if(aValue.isKind(of: NSString.self)){
        return Int((aValue as! NSString).intValue)
    }
    else {
        if aValue is Int {
            return self.object(forKey: aKey) as! Int
        }
        else{
            return Int()
        }
    }
}
func object_forKeyWithValidationForClass_CGFloat(aKey: String) -> CGFloat {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return CGFloat()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return CGFloat()
        }
    } else {
        // KEY NOT FOUND
        return CGFloat()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return CGFloat()
    }
    else {
        if aValue is CGFloat {
            return self.object(forKey: aKey) as! CGFloat
        }
        else{
            return CGFloat()
        }
    }
}
func object_forKeyWithValidationForClass_String(aKey: String) -> String {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return String()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return String()
        }
    } else {
        // KEY NOT FOUND
        return String()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return String()
    }
    else if(aValue.isKind(of: NSNumber.self)){
        return String(format:"%f", (aValue as! NSNumber).doubleValue)
    }
    else {
        if aValue is String {
            return self.object(forKey: aKey) as! String
        }
        else{
            return String()
        }
    }
}
func object_forKeyWithValidationForClass_StringInt(aKey: String) -> String {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return String()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return String()
        }
    } else {
        // KEY NOT FOUND
        return String()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return String()
    }
    else if(aValue.isKind(of: NSNumber.self)){
        return String(format:"%d", (aValue as! NSNumber).int64Value)

    }
    else {
        if aValue is String {
            return self.object(forKey: aKey) as! String
        }
        else{
            return String()
        }
    }
}
func object_forKeyWithValidationForClass_Bool(aKey: String) -> Bool {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return Bool()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return Bool()
        }
    } else {
        // KEY NOT FOUND
        return Bool()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return Bool()
    }
    else {
        if aValue is Bool {
            return self.object(forKey: aKey) as! Bool
        }
        else{
            return Bool()
        }
    }
}
func object_forKeyWithValidationForClass_NSArray(aKey: String) -> NSArray {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return NSArray()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return NSArray()
        }
    } else {
        // KEY NOT FOUND
        return NSArray()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return NSArray()
    }
    else {
        if aValue is NSArray {
            return self.object(forKey: aKey) as! NSArray
        }
        else{
            return NSArray()
        }
    }
}
func object_forKeyWithValidationForClass_NSMutableArray(aKey: String) -> NSMutableArray {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return NSMutableArray()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return NSMutableArray()
        }
    } else {
        // KEY NOT FOUND
        return NSMutableArray()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return NSMutableArray()
    }
    else {
        if aValue is NSMutableArray {
            return self.object(forKey: aKey) as! NSMutableArray
        }
        else{
            return NSMutableArray()
        }
    }
}
func object_forKeyWithValidationForClass_NSDictionary(aKey: String) -> NSDictionary {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return NSDictionary()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return NSDictionary()
        }
    } else {
        // KEY NOT FOUND
        return NSDictionary()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return NSDictionary()
    }
    else {
        if aValue is NSDictionary {
            return self.object(forKey: aKey) as! NSDictionary
        }
        else{
            return NSDictionary()
        }
    }
}
func object_forKeyWithValidationForClass_NSMutableDictionary(aKey: String) -> NSMutableDictionary {
    // CHECK FOR EMPTY
    if(self.allKeys.count == 0) {
        return NSMutableDictionary()
    }
    // CHECK IF KEY EXIST
    if let val = self.object(forKey: aKey) {
        if((val as AnyObject).isEqual(NSNull())) {
            return NSMutableDictionary()
        }
    } else {
        // KEY NOT FOUND
        return NSMutableDictionary()
    }
    // CHECK FOR NIL VALUE
    let aValue : AnyObject = self.object(forKey: aKey)! as AnyObject
    if aValue.isEqual(NSNull()) {
        return NSMutableDictionary()
    }
    else {
        if aValue is NSMutableDictionary {
            return self.object(forKey: aKey) as! NSMutableDictionary
        }
        else{
            return NSMutableDictionary()
        }
    }
}

}

最新更新