我們?cè)陂_(kāi)發(fā)過(guò)程中可能會(huì)遇到一些數(shù)組越界的問(wèn)題泉坐,當(dāng)我們遇到這樣的問(wèn)題的時(shí)候我們可以為NSArray
和NSMutableArray
以及NSDictionary
寫(xiě)一個(gè)分類,我們新建一個(gè)NSArray
的分類,暫且叫做NSArray+Extend
當(dāng)然里面還包含了NSMutableArray
和NSDictionary
逮诲,這樣我們?cè)?code>.h文件中寫(xiě)上一些方法,這里面包含了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
接下來(lái)我們只要在.m
文件中去實(shí)現(xiàn)以下就好了
#import "NSArray+Extend.h"
@implementation NSArray (Extend)
- (id)objectForCheckedKey:(id)key
{
return nil;
}
- (NSString *)stringForCheckedKey:(id)key
{
return @"";
}
//檢查index是否超過(guò)總大小
- (id)objectAtCheckedIndex:(int)index
{
if ([self count] <= index) {
// DLog(@"NSArray數(shù)據(jù)超過(guò)容量");
return nil;
}
else if (index <= -1) {
// DLog(@"index 錯(cuò)誤");
return nil;
}
else
{
return [self objectAtIndex:index];
}
}
- (NSString *)stringAtCheckedIndex:(int)index
{
if ([self count] <= index) {
// DLog(@"NSArray數(shù)據(jù)超過(guò)容量");
return @"";
}
else if (index <= -1) {
// DLog(@"index 錯(cuò)誤");
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ò)請(qǐng)求中取我們想要的值:
[[responseObject objectForCheckedKey:@"error"]stringForCheckedKey:@"message"];
使用方法大同小異,大家可以嘗試使用一下U煨ァ2弁佟Iデ埂!