AbhiRam
AbhiRam

Reputation: 2061

How to create Empty array using for loop in ios

I want to make one empty array using for loop, and for this I wrote below code, but it displays array elements like 1,2,3,4,5 in NSLog statements, but I want to display empty array like ("","","","","")

Here is my code:

arrTemp=[[NSMutableArray alloc]init];   
for (int i = 0; i < 5; i++) {
    [arrTemp addObject:[NSString stringWithFormat:@"%d",i]];
}
NSLog(@"array detais is %@",arrTemp);

Upvotes: 0

Views: 152

Answers (3)

Grazzhopr
Grazzhopr

Reputation: 46

A perfectly correct answer has been provided by Alessandro. However, I think understanding why your solution did not provide the required result would be beneficial to your learning.

In the line: [arrTemp addObject:[NSString stringWithFormat:@"%d",i]];

you are adding a string with the %d format, which indicates an integer. The integer is being provided by your loop: for (int i = 0; i < 5; i++) the first item added is a 0, then a 1,..4; By using empty quotes, you have the solution you are looking for.

[arrTemp addObject:[NSString stringWithFormat:@""]];

You are not using any formatter with your string, so the statement can be simplified into the answer provided by Alessandro

-:[arrTemp addObject:@""];

Upvotes: 0

chiarotto.alessandro
chiarotto.alessandro

Reputation: 1589

Just use the following:

[arrTemp addObject:@""];

Upvotes: 1

wj2061
wj2061

Reputation: 6885

In swift you can do the same in one line of code:

var arrTemp = Array(count: 5, repeatedValue: "")

Upvotes: 0

Related Questions