我们在开发过程中可能会遇到一些数组越界的问题,当我们遇到这样的问题的时候我们可以为NSArray
和NSMutableArray
以及NSDictionary
写一个分类,我们新建一个NSArray
的分类,暂且叫做NSArray+Extend
当然里面还包含了NSMutableArray
和NSDictionary
,这样我们在.h
文件中写上一些方法,这里面包含了NSArray
和NSMutableArray
以及NSDictionary
@interface NSArray (Extend)
- (NSString *)stringForCheckedKey:(id)key;
- (id)objectAtCheckedIndex:(int)index;
- (NSString *)stringAtCheckedIndex:(int)index;
@end
@interface NSMutableArray (Extend)
- (void)addCheckedObject:(id)object;
@end
@interface NSDictionary (Extend)
- (id)objectForCheckedKey:(id)key;
- (NSString *)stringForCheckedKey:(id)key;
@end
接下来我们只要在.m
文件中去实现以下就好了
#import "NSArray+Extend.h"
@implementation NSArray (Extend)
- (id)objectForCheckedKey:(id)key
{
return nil;
}
- (NSString *)stringForCheckedKey:(id)key
{
return @"";
}
//检查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 NSMutableArray (Extend)
- (id)objectForCheckedKey:(id)key
{
return nil;
}
- (void)addCheckedObject:(id)object
{
if (object != nil) {
[self addObject:object];
}
else
{
DLog(@"");
}
}
@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
做完这些我们就能使用了
具体使用方法如下:
1、从网络请求中取我们想要的值:
[[responseObject objectForCheckedKey:@"error"]stringForCheckedKey:@"message"];
使用方法大同小异,大家可以尝试使用一下!!!!
网友评论