2013-04-16 4 views
0

NSmutableArray에 NSString 이름을 추가하고 싶습니다. 그러나 그것에 대해 알지 못합니다. 나는 wamp 서버에 url로부터 5 개의 NSString 이름을 얻었고 NSMutableArray에이 이름들을 추가하고 싶다.NSMutableArray 루프에서 NSString을 추가하는 방법

이것은 내 코드이지만 작동하지 않습니다 !!! : 사전에 배열에 추가됩니다 요소의 수에 대해 확실하지 않은 경우 당신은 NSMutableArray

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

를 할당하지 않는

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??? 
    } 
+3

alloc] init]; NSMutableArray. – Bonnie

+0

같은 파일 이름을 5 번 추가 하시겠습니까? – jkk

답변

4

, 당신이 사용할 수있는 첫째

NSMutableArray *file = [[NSMutableArray alloc] init]; 
3

NSMutableArray 할당되어야합니다.

두 번째로, magic numbers의 사용은 피해야합니다. 더 편리 뭔가

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

을 대체하여

다음, 코드의 가독성이 향상되어야한다. 더욱이 여기의 메모리는 할당되었지만 결코 릴리스되지 않습니다.

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]; 
} 

을하지만, 여기에 우리가 몇 가지 문제를 찾을 수 있습니다 다음과 같이

코드는있을 수 있습니다. 예를 들어 서버 측에서 url을 변경하면 코드를 다시 작성합니다. 요소의 수가 변경되면 동일합니다. 이런 종류의 의존을 피하는 방법을 찾는 것이 좋을 것입니다.

관련 문제