我們在開發(fā)過程中可能會遇到一些數(shù)組越界的問題,當(dāng)我們遇到這樣的問題的時候我們可以為NSArray
和NSMutableArray
以及NSDictionary
寫一個分類,我們新建一個NSArray
的分類,暫且叫做NSArray+Extend
當(dāng)然里面還包含了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
文件中去實現(xiàn)以下就好了
#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數(shù)據(jù)超過容量");
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數(shù)據(jù)超過容量");
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、從網(wǎng)絡(luò)請求中取我們想要的值:
[[responseObject objectForCheckedKey:@"error"]stringForCheckedKey:@"message"];
使用方法大同小異,大家可以嘗試使用一下H褂獭!O魏叶圃!