Thursday, April 10, 2014

iOS snippets part 1

Here are some snippets I use for the iOS platform. Since I work on several platforms (MS Windows, Linux, Android and iOS using languages like C, C#, C++, Obj-C, Java, PHP etc...) , I thought it would be better to put a bunch of useful and often used snippets on my blog, so I don't have to google a lot. Once you understand how to program, it's not important anymore what language you use or what platform you're developing for.

I hope those sinppets are useful for you, let's start :-)


Message Box

- (IBAction)btnExit:(id)sender {
    UIAlertView *messageBox = [[UIAlertView alloc] initWithTitle:@"Exit"
                                                      message:@"Are you sure?"
                                                     delegate:self
                                            cancelButtonTitle:@"No"
                                            otherButtonTitles:@"Yes", nil];
    [messageBox show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
   
    if([title isEqualToString:@"No"]) {
        NSLog(@"No was selected.");
    }
    else if([title isEqualToString:@"Yes"]) {
        NSLog(@"Yes was selected.");
    }
}




Timer 1

- (void) startTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(fireMe) userInfo:nil repeats:YES];
}

- (void) fireMe {
    NSLog(@"I'm fired!");
}


By setting the repeats on YES, makes the timer execute every 0.1 sec which is 100 ms. By setting it to NO, will execute the timer just once.


Timer 2

- (void) startTimer {
    NSTimer *timer = [[ NSTimer alloc ] initWithFireDate: [NSDate dateWithTimeIntervalSinceNow: 0.0
                                                 interval: 0.1
                                                   target: self
                                                 selector: @selector(fireMe)
                                                 userInfo: nil
                                                  repeats: NO];
}


This is another way to start a timer.



Worker-thread using GCD (Grand Central Dispatch)

dispatch_queue_t myQueue = dispatch_queue_create("my queue",NULL);
...
...
...
dispatch_async(imageQueue, ^{
        // This will run the method in a separate thread
        [self doSomeLongRunningTask];
    });


- (void) doSomeLongRunningTask {
    dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We finished a heavy task!");
        });
}


So, we create a dispatch queue handle for our separated thread, than pass a block ^{} to dispatch_async that will be executed in a separate thread ( NOT in the main thread). If you want to call a method in the main thread from another thread, you call:  dispatch_async(dispatch_get_main_queue(), ^{ }); As you see, dispatch_get_main_queue() gives you the queue handle of the main thread.
For more information, check: GDC



Thread with NSThread

NSThread *thread = [[NSThread alloc] initWithTarget:self
                                     selector:@selector(run:)
                                       object:nil];
[thread start];

...
...
- (void) run: (id) object{
    NSLog(@"I'm running in another thread :D");
}


This is a simple example to create another thread and run it by calling the start method.



TCP Sockets with streams

NSInputStream *inputStream;
NSOutputStream *outputStream;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;


CFStreamCreatePairWithSocketToHost( NULL, (__bridge CFStringRef)hostIp, hostPort, &readStream, &writeStream );
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);


inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
...
...
// ope connection
[ inputStream open ];
[ outputStream open ];
...
int len = (int) [outputStream write: buffer maxLength: size];
len = (int) [inputStream read: buffer maxLength: size];


Using streams with NSRunLoop

[inputStream setDelegate:self ]; //This will call stream: handleEvent:

NSRunLoop *runLoop = [ NSRunLoop currentRunLoop ];
[inputStream scheduleInRunLoop: runLoop forMode:NSDefaultRunLoopMode];
[runLoop run]

// This will be called from runLoop
- (void) stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
    switch ( eventCode ) {
        case NSStreamEventOpenCompleted: 

            break;
        case NSStreamEventHasSpaceAvailable:
            break;
        case NSStreamEventHasBytesAvailable:

            break;           
        case NSStreamEventErrorOccurred:
            break;
        case NSStreamEventEndEncountered:
            break;
        default:

    }
}




 

NSNotification example