objective-c 避免数组越界,字典取不到值为空崩溃扩展方法

@interface NSArray (Extend)

- (id)objectAtCheckedIndex:(int)index;

- (NSString *)stringAtCheckedIndex:(int)index;

@end

@interface NSDictionary (Extend)

- (id)objectForCheckedKey:(id)key;

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

@end


//检查index是否超过总大小

- (id)objectAtCheckedIndex:(int)index

{

if ([self count] <= index) {

//        DLog(@"NSArray数据超过容量");

return nil;

}

else if (index <= -1) {

//        DLog(@"index 错误");

return nil;

}

else

{

return [self objectAtIndex:index];

}

}

- (NSString *)stringAtCheckedIndex:(int)index

{

if ([self count] <= index) {

//        DLog(@"NSArray数据超过容量");

return @"";

}

else if (index <= -1) {

//        DLog(@"index 错误");

return @"";

}

else

{

return (NSString *)[self objectAtIndex:index];

}

}

@end


@implementation NSDictionary (Extend)

- (id)objectForCheckedKey:(id)key

{

id object_ = [self objectForKey:key];

if ([object_ isKindOfClass:[NSNull class] ]) {

return nil;

}

return object_;

}

- (NSString *)stringForCheckedKey:(id)key

{

id object_ = [self objectForKey:key];

if ([object_ isKindOfClass:[NSString class] ]) {

return object_;

}

if([object_ isKindOfClass:[NSNumber class] ]) {

return [object_ stringValue];

}

else if ([object_ isKindOfClass:[NSString class] ]) {

return @"";

}

else

{

return @"";

}

}

@end


使用stringForCheckedKey,objectForCheckedKey来取字典便不会崩溃,使用objectAtCheckedIndex,stringAtCheckedIndex便不会越界

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容