Showing posts with label Object C. Show all posts
Showing posts with label Object C. Show all posts

Wednesday, April 25, 2012

The Blocks

Apple introduced blocks (a segment of code that can be executed any time) in C and Objective-c. It happened in Mac OS X 10.6. Later on this feature was back-ported to Mac OS X 10.5 and iPhone by Plausible Labs.  The blocks are also called closures, because they close around variables. Also the blocks can be called lambdas.
I'd say that the blocks are the same as the regular function pointers in C. From a very general point of view, the main difference is just the symbol caret (^) before the block name instead of the asterisk (*) before the function pointer. Here is a trivial example: 

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    @autoreleasepool {

        void (^now)(void) = ^{ 
            NSDate* moment = [NSDate date];
            NSLog(@"Now: %@", moment);
        };
        
        
        now();
    }
    return 0;
}
The program output is: [Switching to process 41322 thread 0x0] 2011-11-26 18:07:25.202 block4[41322:707] Now: 2011-11-26 16:07:25 +0000 Program ended with exit code: 0 The following program simply creates and synchronously performs a block:

Sort String Array

The following code demonstrates how to sort an array of strings in Objective-C:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSArray *stringsArray = [NSArray arrayWithObjects:
                                 @"string 1",
                                 @"String 21",
                                 @"string 12",
                                 @"String 11",
                                 @"String 02", nil];
        static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;
        NSLocale *currentLocale = [NSLocale currentLocale];
        NSComparator finderSort = ^(id string1, id string2) {
            NSRange string1Range = NSMakeRange(0, [string1 length]);
            return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
        };
        
        NSArray* sortedArray = [stringsArray sortedArrayUsingComparator:finderSort];
        NSLog(@"finderSort: %@", sortedArray);        
    }
    return 0;
}
This code is taken from iOS Developer Library.

Accelerometer. It's simple

The simplest way to use accelerometer in an iPhone application is UIAccelerometer class:

    UIAccelerometer* accelerometer = [UIAccelerometer sharedAccelerometer];
This code above shows how to get the accelerometer instance in the code.
The following line sets up the update interval:

    [accelerometer setUpdateInterval1.0 / 10.0f];
    [accelerometer setDelegate:self];
each 0.1 second the accelerometer will update the program that implements delegate method:

 - (void)accelerometer:(UIAccelerometer *)acel didAccelerate:(UIAcceleration *)aceler 
{
    NSLog(@"acceleration.x = %+.6f", aceler.x);
    NSLog(@"acceleration.y = %+.6f", aceler.y);
    NSLog(@"acceleration.z = %+.6f", aceler.z);
}
Do not forget to add UIAccelerometerDelegate, for example, to a view controller class:

Objective-C. Class Extensions.

Few years ago, I was writing my first program in Objective-C, I was surprised that there is no way to add a private method to my class. Encapsulation, one of the basic principles of the OO programming, does not work in Objective-C? Unbelievable.
I found a way to declare a private category in the class main implementation class:

@interface MyClass (Private)
- (void)privateMethod;
@end

Once, by mistake, probably because of this annoying spell checker helping to type code in Xcode, I forgot the category name:


@interface MyClass ()
- (void)privateMethod;
@end

Singleton in iOS Programming

What Apple says about Singleton: 
Cocoa Core Competencies.Singleton 
Creating a Singleton Instance 

What other people say: 
Singletons in Cocoa/Objective-C 
Implementing a Singleton in iOS 
Implementing a Singleton in Objective-C / iOS 
Singleton Classes 
A note on Objective-C singletons 
Singletons, AppDelegates and top-level data. 

A long discussion about it in Stackoverflow: What does your Objective-C singleton look like?

Add Settings to an iOS project

Just find a very nice article about the subject: 
Adding a settings bundle to an iPhone App 

Please pay attention on the paragraph "Even defaults need defaults…" - that's what I needed in my app. Recently I found out that the default values I set for the settings do not work - a boolean parameter is always NO and does not matter that I set it to YES. This boolean parameter gets its default value only when the user opens the application settings for the first time. This article proposes a solution.

The source documentation in the iOS Developer Library: 
Preferences and Settings Programming Guide 

iOS Developer Library proposes an example: FunHouse. Here is a method from this sample:


+ (void)setupDefaults
{
    NSDictionary *userDefaultsValuesDict;
    userDefaultsValuesDict=[NSDictionary dictionaryWithObject:
              [NSNumber numberWithBool:NOforKey:@"useSoftwareRenderer"];
    
    // set them in the standard user defaults
    [[NSUserDefaults standardUserDefaults
              registerDefaults:userDefaultsValuesDict];
}

Find all words in a sentence

This is one of the first samples in Mac OS X Developer Library. I found it in Cocoa Fundamental Guide



#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSArray *param = [[NSProcessInfo processInfoarguments];
        NSCountedSet *cset = [[NSCountedSet allocinitWithArray:param];
        NSArray *sorted_args = [[cset allObjects]
                                sortedArrayUsingSelector:@selector(compare:)];
        NSEnumerator *enm = [sorted_args objectEnumerator];
        id word;
        while (word = [enm nextObject]) {
            printf("%s\n", [word UTF8String]);
        }
        
        [cset release];
        
    }
    return 0;
}

Objective-C. Read text file.

This small program reads the text file:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) 
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString* fileName = @"text.txt";
    NSString *fileString = [NSString stringWithContentsOfFile: fileName];

    NSArray *lines = [fileString componentsSeparatedByString:@"\n"];    

    [pool drain];
    return 0;
}