0

I want to add NSString Name in NSmutableArray but I dont know about that. I get 5 NSString name from url in wamp server and I want add these names in NSMutableArray.

this is my code but do not work!!! :

    NSMutableArray *file;
for (int j=0; j < 5; j++) {
        NSString *fileName = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.101/janatan/filemanager.php?dir=root&file=%d&name",j]]];
        NSLog(@"%@",fileName);
        [file addObject:fileName]  //right???
    } 
2
  • 3
    alloc]init]; your NSMutableArray. Commented Apr 16, 2013 at 8:23
  • Do you like to add same filename for 5 times? Commented Apr 16, 2013 at 8:38

2 Answers 2

4

You are not allocating NSMutableArray

NSMutableArray *file = [[NSMutableArray alloc] initWithCapacity:5];

If you are not sure about the number of elements gets added to array beforehand, you can use

NSMutableArray *file = [[NSMutableArray alloc] init];
Sign up to request clarification or add additional context in comments.

Comments

3

Firstly, the NSMutableArray must be allocated.

Secondly, the using of magic numbers must be avoided.

Next, the readability of code should be improved by replace

NSString *fileName = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.101/janatan/filemanager.php?dir=root&file=%d&name",j]]];

to something more convenient. Moreover, the memory here is allocated but never released.

Your code may be as follows:

const int numberOfFiles = 5;
NSMutableArray *file = [NSMutableArray array]
for(int i = 0; i < numberOfFiles; ++i){
      NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.101/janatan/filemanager.php?dir=root&file=%d&name", i]];
      NSString *fileName = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
      [file addObject:fileName];
 }

But here are we can find some problems. For example if url is changed on server-side you'd rewrite the code. If the number of elements is changed it's the same. So it would be good to find a way to avoid this kind of dependence.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.