WrightsCS
WrightsCS

Reputation: 50717

count .plist dictionary items (iOS SDK)

This is what the plist looks like raw:

{
    authorLastName = Doe;
    authorFirstName = Jane;
    imageFilePath = "NoImage.png";
    title = "Account Test 1";
    year = 2009;
},
{
    authorLastName = Doe;
    authorFirstName = John;
    imageFilePath = "NoImage.png";
    title = "Account Test 2";
    year = 2009;
},

I want to count the total items of a plist, and display them like: '4 Accounts'.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *myPlistPath = [documentsDirectory
                         stringByAppendingPathComponent:@"Accounts.plist"]; 
NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:myPlistPath]; 

NSArray *array = [[plistDict objectForKey:0]
                      sortedArrayUsingSelector:@selector(compare:)]; 

return([NSString stringWithFormat:@"%d Accounts", [array count]]);

However, the result returns 0. I want it to return the ammount of items in the dictionary.

Upvotes: 0

Views: 3180

Answers (3)

Seamus Campbell
Seamus Campbell

Reputation: 17916

That appears to be an old OpenStep property list, which is supported as a read-only format.

Your code looks okay, except that NSDictionary only takes objects as keys, so "[plistDict objectForKey:0]" is not going to do what you expect. If you know the top level of your property list is an array, then assign it to an NSArray, rather than an NSDictionary. If it's actually a dictionary, use a string value for the key, rather than 0.

Upvotes: 0

Amok
Amok

Reputation: 1269

What about [plistDict count]? Since you're passing in 0 as the key to the dictionary you won't get anything back since you can't use nil as a key or a value.

Upvotes: 0

fbrereto
fbrereto

Reputation: 35935

Your return statement is relaying the number of items in the first element of the dictionary, not the number of items of the dictionary itself. Instead what I think what you want is something like:

return [NSString stringWithFormat:@"%d Accounts", [plistDict count]];

Upvotes: 1

Related Questions