开发者

App crashing inserting object into Array

开发者 https://www.devze.com 2023-01-06 14:57 出处:网络
here is the code NSString* favPlistPath = [[NSBundle mainBundle] pathForResource:@\"favs\" ofType:@\"plist\"];

here is the code

NSString* favPlistPath = [[NSBundle mainBundle] pathForResource:@"favs" ofType:@"plist"];
NSMutableDictionary* favPlistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:favPlistPath];

favArray = [[NSMutableArray alloc] initWithCapacity:100];
for(int i=0; i<[favPlistDict count]; i++)
{
    //app is crashing here
    [favArray insertObject:[favPlistDict objectForKey:[开发者_C百科NSNumber numberWithInt:i]] atIndex:i];
}

in my favs.plist file there is single entry key: 0 value: 5


-objectForKey: returns nil if the key doesn't exist in the dictionary. Then when you try to add the object to the array an exception is thrown because you can't add nil to a Cocoa collection.

If you want a placeholder when a value is nil, you must use [NSNull null].

favArray = [[NSMutableArray alloc] init]; 
// the capacity in initWithCapacity: is just a hint about memory allocation, I never bother.

for(int i=0; i<[favPlistDict count]; i++)
{
    id value = [favPlistDict objectForKey:[NSNumber numberWithInt:i]];
    if (value == nil)
    {
        value = [NSNull null];
    }
    [favArray addObject:value]; // adds the object to the end of the array
}

The above works only in the case where the keys in favPListDict are consectuve numbers from 0 to some value.


You are not getting the values correctly from your dictionary. A better approach in these cases is to simply enumerate through the keys in the dictionary, rather than for-looping and hoping there's a value for each number. I also have a feeling you have NSStrings, not NSNumbers, and that is why you're getting nils.

for (NSString *k in favPlistDict) {
    [favArray addObject:[favPlistDict objectForKey:k]];
}

Here, you're adding an object rather than putting it in using insertObject:atIndex: but since you're inserting from 0 and up, addObject: is probably better anyway.

0

精彩评论

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