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便不會越界

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容