I have an array like this
"Customer" = {
"account" = (
"Account_Number" = "00001";
"Products" {
"car= "1"
};
);
开发者_如何学Python "account" = (
"Account_Number" = "00002";
"Products" {
"car= "1"
};
"Products" {
"car= "2"
};
);
};
some customers have one account and some have many and in one account they might have as many products or just one.
what I want is to count how many products in one account. how could I achieve that?
Untested code is as follows:
int count= 0;
for(Account *acc in customer)
{
count += [acc count];
}
check the account no(0001,0002...) everytime and then check no of products for that particular account... means check account no and then in another loop check all products within that loop and have a count in tat loop..
Actually what you can have is:
Customer array. Each element of Customer array is a dictionary. In dictionary you can save an array of products against each account number.
NSMutableArray *customerArray=[[NSMutableArray alloc] init];
... ...
Customer *customer=[customerArray objectAtIndex:i];
[customer setObject:accountNumberArray forKey:@"accountNumbers"];
[customer setObject:productsArray forKey:accountNumber1];
[customer setObject:productsArray forKey:accountNumber2];
.. //where accountNumber can be a string identifying the customer's account.
so to get the count of products for each customer, you can have:
for(Customer *customer in customerArray)
{
int numOfProductsForThisCustomer=0;
NSArray *accountsArray=[customer getObjectForKey:@"accountNumbers"];
for(NSString *accountNumber in accountsArray)
{
NSArray *productsForAccount=[customer getObjecForKey:accountNumber];
int numOfProducts=[productsForAccount count];
numOfProductsForThisCustomer+=numOfProducts;
}
}
//excuse any typos.
Let suppose you have data in customer array then,
NSArray *customer;
int product_count = 0;
NSMutableDictionary *count_dict = [[NSMutableDictionary alloc] init];
for(int i=0; i < [customer count]; i++){
NSArray *account = [customer objectAtIndex:i];
product_count = [account count]-1;
[count_dict addObject:product_count forKey:[account objectAtIndex:0]];
}
All the product count data will be saved in count_dict object with account number as its key.
Here i assume u have compulsary one customer ,account products
NSString *productCount=[NSString stringWithFormat:@"%i",[[[[wholeArray valueForKey:@"Customer"] valueForKey:@"account"] valueForKey:@"Products"] count]];
NSLog(@"count is : %@ \n\n",productCount);
uint c = 0;
NSArray *allProds = [array valueForKeyPath:@"account.Products"];
for(NSArray *prods in allProds) {
c += prods.count;
}
Like @Daij-Djan wrote, KVO Collection is awesome. You can do this all in just one line by using the @count
operator of the KVO Operators
in front of your array:
[array valueForKeyPath:@"@count.account.Products"];
There are some more operator worth to know! Have a look at the NSHipster post to KVO Collection Operators.
精彩评论