Number of occurrences of a substring in an NSString?

This isn’t tested, but should be a good start. NSUInteger count = 0, length = [str length]; NSRange range = NSMakeRange(0, length); while(range.location != NSNotFound) { range = [str rangeOfString: @”cake” options:0 range:range]; if(range.location != NSNotFound) { range = NSMakeRange(range.location + range.length, length – (range.location + range.length)); count++; } }

enum Values to NSString (iOS)

I didn’t like putting the enum on the heap, without providing a heap function for translation. Here’s what I came up with: typedef enum {value1, value2, value3} myValue; #define myValueString(enum) [@[@”value1″,@”value2″,@”value3″] objectAtIndex:enum] This keeps the enum and string declarations close together for easy updating when needed. Now, anywhere in the code, you can use the … Read more

Read a text file line by line in Swift?

Swift 3.0 if let path = Bundle.main.path(forResource: “TextFile”, ofType: “txt”) { do { let data = try String(contentsOfFile: path, encoding: .utf8) let myStrings = data.components(separatedBy: .newlines) TextView.text = myStrings.joined(separator: “, “) } catch { print(error) } } The variable myStrings should be each line of the data. The code used is from: Reading file line … Read more

Converting a string to an NSDate

NSString *dateStr = @”20100223″; // Convert string to date object NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@”yyyyMMdd”]; NSDate *date = [dateFormat dateFromString:dateStr]; // Convert date object to desired output format [dateFormat setDateFormat:@”EEEE MMMM d, YYYY”]; dateStr = [dateFormat stringFromDate:date]; [dateFormat release]; Hope this will help you.

Objective C: convert a NSMutableString in NSString

Either via: NSString *immutableString = [NSString stringWithString:yourMutableString]; or via: NSString *immutableString = [[yourMutableString copy] autorelease]; //Note that calling [foo copy] on a mutable object of which there exists an immutable variant //such as NSMutableString, NSMutableArray, NSMutableDictionary from the Foundation framework //is expected to return an immutable copy. For a mutable copy call [foo mutableCopy] instead. … Read more