Pregunta

I'm looking to loop through my NSArray *urls - to make some string adjustments to each object.

However, once it enters the For Loop and tries to adjust the NSString *thing - this throws an exception.

Any ideas as to why I'm stumped?

 - (void)GetData
    {
        NSFileManager *fm = [NSFileManager defaultManager];
        NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        directory = [NSString stringWithFormat:@"%@/%@/%@/%@", directory, self.researcherID, self.participantID, testTypeString];
        directory = [directory stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSError *error;
        NSURL *url = [NSURL URLWithString:directory];
        NSArray *urls = [fm contentsOfDirectoryAtURL:url includingPropertiesForKeys:nil options:0 error:&error];


        for (int x = 0; x < urls.count; x++) {

            NSString *urlIndex = urls[x];


            NSString *thing = [urlIndex stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
            thing = [thing stringByReplacingOccurrencesOfString:@"file://" withString:@""];


            // add thing to new array but crashes before i can
        }
    }

EDIT: Exception Thrown

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x14ebf1a0'
¿Fue útil?

Solución

NSArray *urls = [fm contentsOfDirectoryAtURL:url includingPropertiesForKeys:nil options:0 error:&error];

returns an array of NSURL objects, not NSStrings. You can convert the URL to a string simply with

NSString *path = [urls[x] path];

that make the string manipulation obsolete. Alternatively, use

NSArray *files = [fm contentsOfDirectoryAtPath:directory error:&error];

which returns an array of NSString objects instead of NSURLs.

Otros consejos

The exception that is thrown makes it quite obvious.

'-[NSURL stringByReplacingOccurrencesOfString:withString:]: unrecognized selector

You are sending the message stringByReplacingOccurrencesOfString:withString: to an objet of class NSURL, which doesn't recognise it. That's the problem.

You are lucky; the call is in your own code, here:

NSString *thing = [urlIndex stringByReplacingOccurrencesOfString:@"%20" withString:@" "];

You assume that urlIndex is an NSString, but actually it is an NSURL, so you have to find the right NSURL method. Just because you assign an array element to an NSString* doesn't make it an NSString*.

In the future: In Xcode, set a breakpoint that triggers on all exceptions, so you will stop before it crashes, when the problem is found. That way you will see the call stack and can find in your code where the problem comes from.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top