开发者

iPhone - Registering an Array containing NSNulls with NSUserDefaults

开发者 https://www.devze.com 2022-12-17 00:30 出处:网络
I have the Array defined below. NSMutableArray *tempMPArray = [NSMutableArray arrayWithCapacity:16]; for (int i=0; i < chapters; i++)

I have the Array defined below.

NSMutableArray *tempMPArray = [NSMutableArray arrayWithCapacity:16];
for (int i=0; i < chapters; i++) 
{

   [tempMPArray addObject:[NSNull null]];
}

Every time I use it as a one of the objects of a dictionary below to register default values it crashes with EXC_BAD_ACCESS.

[[NSUserDefaults standardUserDefaults] registerDefaults:myDict];

If I replace the objects in the array with any other object NSNumber etc it works fine. What am I doing wrong with my array that NSUserDefau开发者_如何学运维lts rejects it ? The stack trace or NSZombie does not give any additional info.


While the solution may be a "work-around" I don't think it answers the underlying question. By providing a dictionary with [NSNull null] values he is providing NSUserDefaults with a valid dictionary. Why is it crashing? Is it something he is doing "wrong" or is it a bug in registerDefaults?

There may be circumstances where it is important to know whether say a user has entered a value (ie there is a valid string) or not entered a value (null) and the method of creating a "valid but empty string" can't determine if the empty string was because the user created a string with no characters or if he had never created a string at all. You may want different logic in these two cases.

I'm in the same boat, I have an NSUserDefault value I want to be [NSNull null] and everything I've read suggests the "right" way to put a null value in a dictionary is with [NSNull null] and my dictionary creates fine. But registerDefaults with this valid dictionary causes a crash. That suggests a bug in the implementation of registerDefaults doesn't it? What is wrong with the following and why does it crash?

NSArray *defaultValues = [NSArray arrayWithObjects:[NSNull null], nil];
NSArray *CurrentKeys = [NSArray arrayWithObjects: @"NullKey", nil];
NSDictionary *resourceDict = [NSDictionary dictionaryWithObjects:defaultValues forKeys:CurrentKeys];
[[NSUserDefaults standardUserDefaults] registerDefaults:resourceDict];

Ultimately, i think the answer is that the userDefaults get written out as a plist and plists don't support NSNull. if that's the case, the documentation for registerDefaults should say that only plist object types are allowed in the dictionary


Here's a better solution!

Define a static after @implementation

NSString *const Null = @"";

Then

NSMutableArray *tempDSArray = [NSMutableArray arrayWithCapacity:16];
 for (i=0; i < chapters; i++) 
 {

  [tempDSArray addObject:Null];
 }

Everything else should work fine!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号