添加空数组时NSUserDefaults崩溃

时间:2014-09-29 12:59:16

标签: objective-c ios8 nsuserdefaults iphone-5

我刚搬到iOS 8,安装了Xcode 6等。 这段代码在iOS 7和6上运行良好。它甚至可以在安装了iOS 8的iPhone 4S上运行。但在iPhone 5和5S上,它崩溃了。 (8.0.0和8.0.2一样) 无论应用程序是针对SDK 7还是8构建,都无关紧要。在同一阶段,这两种情况都会崩溃。

.h文件包含:

@property (nonatomic, strong) NSMutableArray* filterBrandsExclude;
来自.m文件的

// Following lines just to set the conditions for your understanding: 
    _filterBrandsExclude = [[NSMutableArray alloc] initWithCapacity:0]; // just creates an empty array. 
// As a matter of fact, this array may well be empty and it worked nicely on older iOS versions. 

// this line crashes: 
    [userDefaults setObject:_filterBrandsExclude forKey:@"filterBrandsExclude"];

错误讯息:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSKeyValueSlowMutableArray getObjects:range:]: value for key filterBrandsExclude of object 0x17004ae00 is nil'
*** First throw call stack:
(0x1885c6084 0x198bac0e4 0x1885c5fc4 0x18946097c 0x189460a68 0x189460ab0 0x1884c24d0 0x18854be90 0x1884c21c0 0x1884c17e8 0x188627c80 0x188552d9c 0x188551e9c 0x188600290 0x1885ff840 0x1886030e4 0x1893bb750 0x100053e5c 0x1000522a4 0x18cfd65d4 0x18cfdead0 0x18cfdea58 0x18cfd238c 0x1907d1640 0x18857e360 0x18857d468 0x18857ba8c 0x1884a9664 0x1915eb5a4 0x18cdae984 0x1000515f4 0x19921aa08)
libc++abi.dylib: terminating with uncaught exception of type NSException

任何想法都表示赞赏。

2 个答案:

答案 0 :(得分:0)

两件事。

  1. 在您的错误中,它表示密钥filterBrandsInclude的值为nil,但在您的问题中,您引用了密钥filterBrandsExclude。您确定此时已经确定了实际错误吗?
  2. 编辑:第2点无效。

答案 1 :(得分:0)

你可以手动检查

if(self.filterBrandsExclude != nil && self.filterBrandsExclude.count > 0)
    [userDefaults  setObject:_filterBrandsExclude forKey:@"filterBrandsExclude"];
else
   [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"filterBrandsExclude"];