HD-VRSCA
HD-VRSCA

Reputation: 33

Fast Enumeration error?

Getting a warning saying that:

Collection expression type 'NSString *' may not respond to 'countByEnumeratingWithState:objects:count'

when trying to run the following code:

 NSString *proper = [NSString stringWithContentsOfFile:@"usr/share/dict/propernames"     encoding:NSUTF8StringEncoding error:NULL];


for (NSString *i in proper){
        NSLog(@"Item>%@", i);
        }

When I run the program I don't get any output from the NSLog statement. Anyone run into this?

Upvotes: 1

Views: 1771

Answers (3)

aroth
aroth

Reputation: 54856

The compiler warning is trying to tell you that you cannot iterate over an NSString using a for ... in ... loop. It is further trying to say than the reason for this is that an NSString is not a valid "Collection" type. Your valid "Collection" types are things like NSArray, NSSet, and NSDictionary.

So if your file is supposed to contain structured data, you should parse it into something more useful than a flat NSString. Something like this may give a better result:

NSString* temp = [NSString stringWithContentsOfFile:@"usr/share/dict/propernames"     encoding:NSUTF8StringEncoding error:NULL];
NSArray* proper = [temp componentsSeparatedByString:@"\n"];

for (NSString* i in proper){
    NSLog(@"Item>%@", i);
}

That will print each line in the file. This assumes, of course, that your input file has one entry per line. If it is structured some other way, then you will have to parse it differently.

Upvotes: 3

Ehab Amer
Ehab Amer

Reputation: 392

This is a clear mistake u have here. NSString* is a string object and is not a collection of characters as the string object known in C++ which is a character array. for-in Loop need a collection to iterate within. like NSArray or NSSet.

Upvotes: 0

bneely
bneely

Reputation: 9093

After you load the file, split it into lines with componentsSeparatedByString: .

NSArray *lines = [proper componentsSeparatedByString:@"\n"]; // Use the correct line ending character here
for (NSString *i in lines) {
    NSLog(@"item> %@", i);
}

Upvotes: 0

Related Questions