Showing posts with label Cocoa. Show all posts
Showing posts with label Cocoa. Show all posts

Wednesday, April 25, 2012

Cocoa: Binding. GUI application without outlets


Outlet in Cocoa is a persistent reference to a GUI control. For example, it is a common way to create the outlet to the text field and change the text in this field via the outlet. Now, in 64-bit Xcode, you add a property with IBOutlet keyword, synthesize it, and set new text via that property:

1. In interface declaration:
@property (retainIBOutlet NSTextField * text;

2. In the implementation section:
@synthesize text;

3. Set new text to the text field:

text.stringValue = @"Hello, World!";

4. Get value:

NSString* str = text.stringValue;

Cocoa: show Alert

Show Alert in a Cocoa application:



- (IBAction)showAlert:(id)sender
{
NSString *question = NSLocalizedString(@"Do you see this alert?"
   @"Let's verify that I see this question");
NSString *info = NSLocalizedString(@"I hope, I see this alert"
           @"Here is an info");
NSString *cancelButton = NSLocalizedString(@"Cancel"
   @"Cancel button title");
NSAlert *alert = [[NSAlert allocinit];
[alert setMessageText:question];
[alert setInformativeText:info];
[alert addButtonWithTitle:cancelButton];
NSInteger answer = [alert runModal];
[alert release];
alert = nil;
}

Cocoa: NSScanner

sscanf is a standard C function. We use it so rarely, but it exists and can be the fastest method to parse a string. In order to remind I post this short program that uses sscanf to retrieve two float number from a string:

#include <stdio.h>

int main (int argc, const char * argv[]) 
{
    float x, y;
    const char* string = "3.1415 6.28";
    sscanf(string, "%f %f", &x, &y);
    printf("x = %.4f, y = %.2f\n", x, y);
    return 0;
}

Template program to learn Cocoa graphics

The standard way to learn new programming language is very boring for me - endless reading of heavy books, typing useless programs that calculates factorials,... Since my student times, since GWBASIC I begin from the graphics, simple graphic, rectangles, circles - the graphic primitives. When I know how to draw them, I can go on and learn the basic language constructions, language semantic and programming techniques.
This way works for me in my Cocoa period. In this post I'd like to show two methods to create a template project that allows to learn the Cocoa graphical primitives. This template can grow in your hands and become a real Cocoa (or Coco Touch) application.
As any Cocoa application this application has a main window and a view inside. That's all. First method uses Interface Builder. The second one fully ignores the Interface Builder.

Cocoa: Implicit Animation


This program will help to begin with the Core Animation.
1. In Xcode create Max OS X Cocoa Application.
2. In the Application delegate implementation file (automatically created by Xcode on Snow Leopard) add a button to the content view:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{
    // Create new button in content view.
    NSRect frame = NSMakeRect(10, 40, 90, 40);
    NSButton* pushButton = [[NSButton alloc] initWithFrame: frame];
    pushButton.bezelStyle = NSRoundedBezelStyle;
    [pushButton setTitle: @"Move"];
    [self.window.contentView addSubview: pushButton];
    
    // Set the button target and action.
    pushButton.target = self;
    pushButton.action = @selector(move:);
    
    [pushButton release];
}

Save and Load UIImage in Documents directory on iPhone


The following function saves UIImage in test.png file in the user Document folder:
- (void)saveImage: (UIImage*)image
{
    if (image != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                      NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent: 
                       [NSString stringWithString: @"test.png"] ];
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
    }
}

Create Bitmap Graphics Context on iPhone


The following function creates an UIImage object:
- (UIImage*)makeImage: (CGRect)rect
{
    CGFloat width = CGRectGetWidth(rect);
    CGFloat height = CGRectGetHeight(rect);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    size_t bitsPerComponent = 8;
    size_t bytesPerPixel    = 4;
    size_t bytesPerRow      = (width * bitsPerComponent * bytesPerPixel + 7) / 8;
    size_t dataSize         = bytesPerRow * height;
    
    unsigned char *data = malloc(dataSize);
    memset(data, 0, dataSize);

    CGContextRef context = CGBitmapContextCreate(data, width, height, 
                bitsPerComponent, 
                bytesPerRow, colorSpace, 
                kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    
    CGColorSpaceRelease(colorSpace);
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    UIImage *result = [[UIImage imageWithCGImage:imageRef] retain];
    CGImageRelease(imageRef);
    CGContextRelease(context);
    free(data);    
    return result;
}

Make a snapshot from an iPhone application


Today I needed to make a snapshot programmatically. I thought it's easy:
[iPhone developer:tips];. Screen Capture using UIGetScreenImage.
Unfortunately, this approach does not work for me. People say that this API is private.
Ok. Let's make our own function.
I will add this function to my application delegate class. It looks so:
@interface myDelegate : NSObject<UIApplicationDelegate>
{
    UIWindow* window;
}

- (void) makeSnapshot;

@end

Cocoa. Date and Time

This small program below detects the current date:

#import <Foundation/Foundation.h>

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

     NSDate* today = [[NSDate alloc] init];
     NSLog(@"today is: %@", today);
    
    [today release];        
    [pool drain];
    return 0;
}
In the console you'll see:

run
[Switching to process 12401 local thread 0x3f03]
Running…
2010-03-06 17:05:45.217 DayOfToday[12401:a0f] today is: 2010-03-06 17:05:45 +0200

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: