[英]how to add NSString from loop in NSMutableArray
I want to add NSString Name in NSmutableArray but I dont know about that. 我想在NSmutableArray中添加NSString名称,但我对此一无所知。 I get 5 NSString name from url in wamp server and I want add these names in NSMutableArray. 我从wamp服务器的url中获得5个NSString名称,我想在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???
}
You are not allocating NSMutableArray
您没有分配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];
Firstly, the NSMutableArray
must be allocated. 首先,必须分配NSMutableArray
。
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. 例如,如果在服务器端更改了url,则将重写代码。 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. 因此,找到一种避免这种依赖性的方法将是很好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.