Reputation: 13
Does anyone have any idea why the following causes the program to crash?
NSFileManager *filemgr;
NSString *currentpath = [filemgr currentDirectoryPath];
NSArray *filelist;
filemgr = [NSFileManager defaultManager];
filelist = [filemgr contentsOfDirectoryAtPath:currentpath error:nil];
int count=[filelist count];
for (int i = 0; i < count ; i++)
NSLog (@"%@", [filelist objectAtIndex: 1]);
As an added note, I am redirecting NSLog().
Upvotes: 1
Views: 213
Reputation: 9392
I think your crash message comes from your 2nd line where it you're asking for the current directory. However, you allocated the variable on the 4th line, which is probably why it crashed. Instead, you should rearrange your code to something like this.
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *currentpath = [filemgr currentDirectoryPath];
From what I see you're doing, you're declaring all of your variables first, which is why the error occurred. In Objective-C, it doesn't matter where you declare your variables, but you must allocate and initialize it before you can use them.
Upvotes: 2
Reputation: 52227
I think you meant
for (int i = 0; i < count ; i++)
NSLog (@"%@", [filelist objectAtIndex: i]);
(i instead of 1)
You also can do it
for (NSString *path in filelist)
NSLog(@"%@", path);
This is called fast enumeration and should be chosen, if possible, over the traditional c-style for-loop.
Upvotes: 0
Reputation: 21373
It's probably this line:
NSLog (@"%@", [filelist objectAtIndex: 1]);
Presumably you mean:
NSLog (@"%@", [filelist objectAtIndex: i]);
If filelist contains less than 2 objects, [filelist objectAtIndex:1] will crash, because you're trying to access an index beyond the end of the array.
Note: You'll get better answers by posting details of the exact error message you're seeing.
Upvotes: 2