iPhone Development 101
This domain is for sale.

iPhone 101

Code Tips

Resources

More

Use the NSString method rangeOfString to determine whether a substring exists within a string:

NSString *theString = @"fnord.com";
NSRange isCom = [theString rangeOfString:@".com"];
// tldr is now { 5, 4 }

NSRange is a struct with two parts:

	.location
	.length

If a substring is not found, rangeOfString returns {NSNotFound, 0}.

A shorter way of testing whether a string contains a substring:

if ( [theString rangeOfString:@".com"].location != NSNotFound ) {
    // do something if the string is found
}

Replacing (or removing) a Substring:

NSString *theString = @"fnord.com";
NSRange tldr = [domainName rangeOfString:@".com"];

if (tldr.location != NSNotFound) {
    NSLog(@"range of .com: %d, %d", tldr.location, tldr.length);
    domainName = [domainName stringByReplacingCharactersInRange:tldr withString:@""];
    NSLog(@"removed .com, domain is now: %@", domainName);
}

Getting the User's Name from the UIDevice string

The method [[UIDevice currentDevice] name] returns a string containing the user's device name, e.g. "Steve's iPhone 5" or "Jim's iPad". Here's how to get the user's name from this string:

    NSString *deviceName = [[UIDevice currentDevice] name];
    NSString *actualName = deviceName;
    
    NSRange range = [deviceName rangeOfString:@"'s "];
    if (range.location != NSNotFound) {
        actualName = [deviceName substringToIndex:range.location];
    }
    NSLog(@"user's name: %@", actualName);

More String Functions

Additional References

TopHome