gpt4 book ai didi

ios - objectForKey 空检查

转载 作者:行者123 更新时间:2023-11-29 03:07:09 25 4
gpt4 key购买 nike

正在尝试检查项目中数据的有效性(项目是 NSDictionary)

我认为这应该可行,但我确实进入了第二个 if 并崩溃了:
发送到实例的无法识别的选择器因为 galleryArr(null)

    NSArray *galleryArr = [item objectForKey:@"photos"];

if (galleryArr != nil ) {
if ([galleryArr count] != 0) {
//do something
}
}

有什么想法吗?

最佳答案

我用一个简单的 Objective-C 类别解决了这个问题:

NSDictionary+NotNull.h

#import <Foundation/Foundation.h>

/*! This category extends NSDictionary to work around an issue with NSNull object.
*/
@interface NSDictionary (NotNull)

/*! @abstract Returns the value associated with a given key, but only if the value is not NSNull.
@param aKey The key for which to return the corresponding value.
@return The value associated with the given key, or nil if no value is associated with the key, or the value is NSNull.
*/
- (id)objectOrNilForKey:(id)aKey;

@end

NSDictionary+NotNull.m

#import "NSDictionary+NotNull.h"

@implementation NSDictionary (NotNull)

- (id)objectOrNilForKey:(id)aKey
{
id object = [self objectForKey:aKey];
if (object == [NSNull null]) {
return nil;
}
return object;
}

@end

现在您只需调用:

NSArray *galleryArr = [item objectOrNilForKey:@"photos"];

关于ios - objectForKey 空检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22639849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com