Fast Enumeration error? - ios

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?

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.

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

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.

Related

Unknown quotation marks added to string object in NSMutableArray after for loop

I have an array of NSString objects, the objects have some unneccessary chars (one object looks like this in the console: "\"stringContent\"") that I'm removing with the below code. It works correctly, however when I log arr1 50-60% of the strings got a quotation marks like this "stringContent", the others don't have it. Actually my problem is that I don't have an why it happens, because when I log the strings in the for loop they don't have the quotation marks. Do anybody has an idea what can causes this?
NSMutableArray * arr1 = [[NSMutableArray alloc ]init];
for (NSString *str in self.stringArray) {
NSString *newString = [str substringToIndex:[brand length]-1];
NSString *nwstr = [newString substringFromIndex:1];
[arr1 addObject:nwstr];
NSLog(#"string %#", nwstr);
}
NSLog(#"array %#", arr1);
Other thing that might be helpful, when I call this every object appears in the console, it's like the quotation marks are hidden for the containsString method, because a lot of them don't meet the requirement of the if statement.
for (NSString *str in arr1) {
if (![str containsString:#"\""]) {
NSLog(#"XXX %#", str);
}
}
When you NSLog an NSArray or NSDictionary, the elements are displayed in a log format which MAY (or may not) include gratuitous quotation marks, escaped characters, etc. Specifically, quotation marks are used around strings, EXCEPT when the strings contain no non-alphabetic characters or blanks.
More detail: What actually happens is that NSLog internally invokes [NSString stringWithFormat:] or one of its kin to format the text to be logged. stringWithFormat:, in turn, invokes the description method of each object in the parameter list that corresponds to a %# format directive. It is the description method of NSArray and NSDictionary which adds the extra characters.

Loop through lines in file and fill NSMutable array with NSStrings

I have an array, lines, that consists of the lines in a text file. I want to choose a particular line based on its first string. So I loop through the file like this:
for(NSString *str in lines)
{
myMutableArray = [str componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#";"]];
//Get myMutableArray[0] and check if it's the correct line
// If not, empty the NSMutableArray and start over
}
I know that the code line inside the loop will return an NSArray, so this won't work. What is the best way to solve this problem?
Hank
myMutableArray = [[str componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:#";"]] mutableCopy];
Suits?

CSV to NSString results in empty null object

I'm trying to retrieve content of a csv file to NSString. Thats what I do:
NSString *strBundle = [[NSBundle mainBundle] pathForResource:#"socs" ofType:#"csv"];
NSLog(#"bundle path: %#",strBundle);
NSString *file = [NSString stringWithContentsOfFile:strBundle
encoding:NSUTF8StringEncoding
error:nil];
if ([[NSFileManager defaultManager]fileExistsAtPath:strBundle]) {
NSLog(#"file is there!!!");
}else {
NSLog(#"no file");
}
NSLog(#"file: %#",file);
NSArray *allLines = [file componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(#"lines: %lu",(unsigned long)[allLines count]);
file manager shows that the file is there. When i try to log the NSString or number of files it says null. I even created NSData object with the content of exactly the same file and when I logged the NSData object, I clearly saw that there is some data. Then when I tried to create NSString with the content of NSData, I had the same result as before - null. Maybe the problem is somewhere in the formatting of the file?
Any help will be appreciated :)
I see 3 issues:
You are passing a nil argument to the error: parameter in your stringWithContentsOfFile: line. If there's a possibility something might go wrong (and apparently there is), you should pass a real argument there so you can figure out what went wrong.
You can use componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet], but that has a tendency to produce blank "components" between every line. Plain old #"\n" works better in virtually all cases I've run into.
You should be checking fileExistsAtPath before you try to load it into the NSString
If you were truly able to create an NSData object from the path it doesn't necessarily mean it's correct data. But let's say it is, if you were not able to convert it to a NSString then you need to check your encoding parameter.

NSString characterSetWithCharactersInString returns empty strings

I'm trying to break a NSString into the comma separated components. Somehow my NSString containing 25000 components always returns 25.500 values, 500 of which are empty NSStrings. Here's what my code looks like:
NSString* fileContents = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:nil];
/* do stuff */
NSMutableArray* components =
[NSMutableArray arrayWithArray:
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#",\n\r "]]];
Consider this example:
[#"\n,\n"componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#",\n\r "]];
The result shows how componentsSeparatedByCharactersInSet: behaves. Four components, all empty strings. Do you see why?
I'm not quite sure what you were expecting it to do, but that is what it does do. It just splits at any of the characters you list. If two of them are next to each other, you get an empty string. Plus a string for before the first one and a string for after the last one.
So the reason you are getting 25500 components is that, given the command you gave, that is how many components there are.

Accented character incorrectly encoding in NSString Array

?I'm building a NSMutableArray of NSStrings from a list and some of the letters are accented (Turkish). I have been able to encode into a NSString and NSLog the results. But when I add that NSString to my NSMutableArray the encoding is incorrect.
This works:
NSString* temp = [[NSString alloc] init];
char *str = "üç";
temp = [NSString stringWithUTF8String:"üç"];
NSLog(#"str: %#",temp);
Logged output:
2012-06-09 09:09:18.398 Fluent[1821:f803] str: üç
When I try to add it to my NSMutableArray like this:
ones = [NSArray arrayWithObjects:#"",#"bir",#"iki",temp,#"dört",#"beş",#"altı",#"yedi",#"sekiz",#"dokuz",nil];
NSLog(#"ones: %#",ones);
It loses the encoding:
2012-06-09 09:09:18.399 Fluent[1821:f803] ones: (
"",
bir,
iki,
"\U00fc\U00e7",
"d\U00f6rt",
"be\U015f",
"alt\U0131",
yedi,
sekiz,
dokuz)
Any ideas on how to do this? The posts I have read around this area seem to be focused on transfer over HTTP.
I'd like a simpler approach such as to encode a C-string if this is necessary and then unstring by spaces into the array.
Your strings aren't incorrectly encoded. What you see is an artifact of writing a complete array to the log. In this case, the array is first converted to the property list format and then written to the log.
If you create a loop and write each element separately to the log, you'll see that everything is ok:
NSUInteger count = [ones count];
for (NSUInteger i = 0; i < count; i++) {
NSLog(#"element %d: %#", i, [ones objectAtIndex: i]);
}
This is not losing the encoding, try to add the strings from the nsarray to a UILabel or UITextField and it should be correct
This behavior of writing the Unicode representation happens only in the console when you NSLog

Resources