Async NSURLConnection in iOS

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    dispatch_semaphore_t sem;
    NSMutableData *alldata;
}

@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    sem = dispatch_semaphore_create(0);
    alldata = [[NSMutableData alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    [alldata appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    dispatch_semaphore_signal(sem);
}

- (IBAction)clicked:(id)sender {
    //run clickThread function in a separate thread
    [self performSelectorInBackground:@selector(clickThread) withObject:nil];
}

- (void) makeconnection:(NSString*)url {
    NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:url]];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void) clickThread {
    NSLog(@"making connection with google");
    //NSURLConnection will only work if it is run on the main thread
    [self performSelectorOnMainThread:@selector(makeconnection:) withObject:@"http://www.google.com" waitUntilDone:NO];
    
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    NSLog(@"google done");
    NSLog(@"%@", [[NSString alloc] initWithData:alldata encoding:NSUTF8StringEncoding]);
    
    NSLog(@"making connection with yahoo");
    sem = dispatch_semaphore_create(0);
    alldata = [[NSMutableData alloc] init];
    [self performSelectorOnMainThread:@selector(makeconnection:) withObject:@"http://www.yahoo.com" waitUntilDone:NO];
    
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    NSLog(@"yahoo done");
    NSLog(@"%@", [[NSString alloc] initWithData:alldata encoding:NSUTF8StringEncoding]);
}
@end

Parsing address using Regular Expressions

Objective-C

    NSString *address = @"123 Main Street, New York, NY 10001";
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]+[A-Za-z\\s]+," options:NSRegularExpressionCaseInsensitive error:&error];
    [regex enumerateMatchesInString:address options:0 range:NSMakeRange(0, address.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
        NSString *street = [address substringWithRange:result.range];
        street = [street stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
        NSLog(@"street: %@", street);
    }];
    
    regex = [NSRegularExpression regularExpressionWithPattern:@",[A-Za-z\\s]+," options:NSRegularExpressionCaseInsensitive error:&error];
    [regex enumerateMatchesInString:address options:0 range:NSMakeRange(0, address.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
        NSString *city = [address substringWithRange:result.range];
        city = [city stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]];
        NSLog(@"city: %@", city);
    }];
    
    regex = [NSRegularExpression regularExpressionWithPattern:@",[\\s]*[A-Z]{2}[\\s]" options:NSRegularExpressionCaseInsensitive error:&error];
    [regex enumerateMatchesInString:address options:0 range:NSMakeRange(0, address.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
        NSString *state = [address substringWithRange:result.range];
        state = [state stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]];
        NSLog(@"state: %@", state);
    }];
    
    regex = [NSRegularExpression regularExpressionWithPattern:@"[\\s][0-9]{5}" options:NSRegularExpressionCaseInsensitive error:&error];
    [regex enumerateMatchesInString:address options:0 range:NSMakeRange(0, address.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop){
        NSString *zip = [address substringWithRange:result.range];
        zip = [zip stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]];
        NSLog(@"zip: %@", zip);
    }];

Swift

var error:NSError?
let address:NSString = "123 Main Street, New York, NY 10001"
var regex = NSRegularExpression(pattern: "^[0-9]+[A-Za-z\\s]+,", options:.CaseInsensitive, error: &error)
regex?.enumerateMatchesInString(address, options: .WithTransparentBounds, range: NSMakeRange(0, address.length)) {
    (result: NSTextCheckingResult! , _, _) in
    var street:NSString = address.substringWithRange(result.range)
    street = street.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: ","))
    NSLog("street: %@",street);
}

regex = NSRegularExpression(pattern: ",[A-Za-z\\s]+,", options:.CaseInsensitive, error: &error)
regex?.enumerateMatchesInString(address, options: .WithTransparentBounds, range: NSMakeRange(0, address.length)) {
    (result: NSTextCheckingResult! , _, _) in
    var city:NSString = address.substringWithRange(result.range)
    city = city.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: ", "))
    NSLog("city: %@",city);
}

regex = NSRegularExpression(pattern: ",[\\s]*[A-Z]{2}[\\s]", options:.CaseInsensitive, error: &error)
regex?.enumerateMatchesInString(address, options: .WithTransparentBounds, range: NSMakeRange(0, address.length)) {
    (result: NSTextCheckingResult! , _, _) in
    var state:NSString = address.substringWithRange(result.range)
    state = state.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: ", "))
    NSLog("state: %@",state);
}

regex = NSRegularExpression(pattern: "[\\s][0-9]{5}", options:.CaseInsensitive, error: &error)
regex?.enumerateMatchesInString(address, options: .WithTransparentBounds, range: NSMakeRange(0, address.length)) {
    (result: NSTextCheckingResult! , _, _) in
    var zip:NSString = address.substringWithRange(result.range)
    zip = zip.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: ", "))
    NSLog("zip: %@",zip);
}

NSPredicate in Objective-C

    NSMutableArray *arr = [[NSMutableArray alloc]init];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setValue:@"JFK Airport" forKey:@"airport"];
    [dict setValue:@"Queens" forKey:@"location"];
    [arr addObject:dict];
    
    dict = [[NSMutableDictionary alloc]init];
    [dict setValue:@"LGA Airport" forKey:@"airport"];
    [dict setValue:@"Queens" forKey:@"location"];
    [arr addObject:dict];
    
    dict = [[NSMutableDictionary alloc]init];
    [dict setValue:@"Empire State Building" forKey:@"building"];
    [dict setValue:@"Manhattan" forKey:@"location"];
    [arr addObject:dict];
    
    dict = [[NSMutableDictionary alloc]init];
    [dict setValue:@"Coney Island" forKey:@"landmark"];
    [dict setValue:@"Brooklyn" forKey:@"location"];
    [arr addObject:dict];
    
    NSPredicate *p = [NSPredicate predicateWithFormat:@"airport endswith 'Airport'"];
    NSArray *filtered = [arr filteredArrayUsingPredicate:p];
    NSLog(@"%@\n", filtered);
    
    p = [NSPredicate predicateWithFormat:@"location = 'Manhattan'"];
    filtered = [arr filteredArrayUsingPredicate:p];
    NSLog(@"%@\n", filtered);
    
    p = [NSPredicate predicateWithFormat:@"building contains 'State'"];
    filtered = [arr filteredArrayUsingPredicate:p];
    NSLog(@"%@\n", filtered);
    
    p = [NSPredicate predicateWithFormat:@"location = 'Manhattan' OR location = 'Brooklyn'"];
    filtered = [arr filteredArrayUsingPredicate:p];
    NSLog(@"%@\n", filtered);

Palindrome in Objective-C

Solution to Project Euler problem 4

#import <Foundation/Foundation.h>

bool isPalindrome(NSString *x)
{
    NSInteger i = 0;
    NSUInteger j = [x length] - 1;
    while (i <= j)
    {
        if ([x characterAtIndex:i] != [x characterAtIndex:j])
            return false;
        i++;
        j--;
    }
    return true;
}

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        int max = 0;
        for (int i = 100; i < 1000; i++) {
            for (int j = 100; j < 1000; j++) {
                int prod = i * j;
                NSString *prodStr = [NSString stringWithFormat:@"%i", prod];
                if (isPalindrome(prodStr) && prod > max) {
                    max = prod;
                }
            }
        }
        
        NSLog(@"%i", max);
    }
    return 0;
}