NewSafeObject.m 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // NewSafeObject.m
  3. // MingMen
  4. //
  5. // Created by 罗云飞 on 2017/3/9.
  6. // Copyright © 2017年 罗云飞. All rights reserved.
  7. //
  8. #import "NewSafeObject.h"
  9. @implementation NSArray (SafeObjectAtIndex)
  10. - (id) safeObjectAtIndex : (NSUInteger) index
  11. {
  12. if (self.count > 0 && self.count > index)
  13. {
  14. return [self objectAtIndex:index];
  15. }
  16. else
  17. {
  18. return NULL;
  19. }
  20. return NULL;
  21. }
  22. - (NSInteger)safeCount{
  23. if (self == nil && [self isKindOfClass:[NSNull class]]) {
  24. return 0;
  25. }
  26. return self.count;
  27. }
  28. @end
  29. @implementation NSDictionary (SafeObjectForKey)
  30. - (id) safeObjectForKey : (NSString *) key
  31. {
  32. if (self.count > 0 && [[self allKeys] containsObject:key])
  33. {
  34. return [self objectForKey:key];
  35. }
  36. return nil;
  37. }
  38. @end
  39. @implementation NSMutableDictionary (SafeObjectForKey)
  40. - (void) safeSetObject:(id)value forKey:(NSString*)key
  41. {
  42. if ([value isKindOfClass:[NSNull class]]) {
  43. value = @"";
  44. }
  45. return [self setObject:NewSafeString(value) forKey:NewSafeString(key)];
  46. }
  47. - (void) safeUTF8SetObject:(id)value forKey:(NSString*)key
  48. {
  49. if ([value isKindOfClass:[NSNull class]]) {
  50. value = @"";
  51. }
  52. return [self setObject:NewSafeString([value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]) forKey:NewSafeString(key)];
  53. }
  54. - (void) safeJSONSetObject:(id)value forKey:(NSString*)key
  55. {
  56. //成就数组转Json字符串
  57. NSError *error = nil;
  58. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:value options:NSJSONWritingPrettyPrinted error:&error];
  59. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  60. return [self setObject:NewSafeString(jsonString) forKey:NewSafeString(key)];
  61. }
  62. @end