开发者

Loading values into an array from two different arrays iphone sdk

开发者 https://www.devze.com 2023-04-07 15:12 出处:网络
Here I am having a situation, I\'m using the following code: int x=0; for (int i=0; i<=[arrayDeals count]-1; i++) {

Here I am having a situation, I'm using the following code:

int x=0;
for (int i=0; i<=[arrayDeals count]-1; i++) {
    x++;
    //NSString *deal = [arrayDeals objectAtIndex:i];
    combinedArr = [[NSMutableArray alloc]initWithObjects:
                    [CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];
}

I need to load the values from arrayDeals and the 'x' value into combinedArr. So, I put this in a for loop. But i got only one value from each arrays. What is went wrong here? Ple开发者_C百科ase help me. (here CustomObject is a NSObject) Thank you.


Well there are many things wrong with the code you posted, but I think this is what you want:

int x = 0;

NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:
NSInteger count = [arrayDeals count];
for (int i = 0; i < count; i++) {
    x++;
     CustomObject *customObject =  [CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x];

   [combinedArr addObject:customObject];
}

To give you some idea of what is wrong with the code you posted:

combinedArr = [[NSMutableArray alloc]initWithObjects:
                    [CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];

Here you create a new NSMutableArray to which you assign an new object to taked the object from the array arrayDeals. But you create this NSMutableArray for every item in the array arrayDeals and you assign them to the same variable.

So each iteration you leak the NSMutableArray.

Also :

for (int i=0; i<=[arrayDeals count]-1; i++) {

is the same as

 for (int i=0; i < [arrayDeals count]; i++) {

but the count is called every time you iterate, so as per my example I saved the count in a int to just speed things up.


You could even speed the code up using fast Enumeration:

NSInteger x = 0;    
NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:

for (id object in arrayDeals) {
    id secondObject = [secondArray itemAtIndex:x];
    // Arrays start at 0 so only up it after we've got the object.
    x++;
     CustomObject *customObject =  [CustomObject customObjectWithName:object andNumber:x];

   [combinedArr addObject:customObject];
}
0

精彩评论

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