Simple way to implement multi-thread

I want show you simple way to create multi-thread calculations in few strings of code.

Simple collection of operations. But remember about blocks specifications and use proper storage type.

1
2
3
4
5
6
7
NSMutableArray *operations = [NSMutableArray array];
    for (...) {
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
           // calculation
        }];
        [operations addObject:operation];
    }

If you don’t like blocks, you can easily make a subclass of NSOperation and overwrite main function.

Now time to create queue for operations, so just create instance of NSOperationQueue.
And in maxConcurrentOperationCount property you need setup proper value. For example 2, if you want to use just 2 concurrent threads for your calculations and continue in normal state with others operations in another threads.
In this case waitUntilFinished should be NO.

But if you want to use max threads of CPU, setup NSOperationQueueDefaultMaxConcurrentOperationCount to maxConcurrentOperationCount and YES to waitUntilFinished. Like in example below:

1
2
3
4
5
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:....];
    [queue addOperations:operations waitUntilFinished:YES];
    [queue waitUntilAllOperationsAreFinished];
    [operations removeAllObjects];

If this is set, it will choose an appropriate value based on the number of available processors and other relevant factors.

1
2
3
enum {
  NSOperationQueueDefaultMaxConcurrentOperationCount = -1
};

NSOperationQueueDefaultMaxConcurrentOperationCount: The default maximum number of operations is determined dynamically by the NSOperationQueue object based on current system conditions.

That it! It’s so simple today.


Project based on DETweetComposeViewController

Facebook connection with Facebook SDK 3.0.x (last at 2 september 2012)

What is it?
DEFacebookComposeViewController is an iOS 4 compatible composer view for posting picture and message on user wall.
Looks like the Facebook Sheet in iOS 6.

How to use:
1. download and setup Facebook sdk

2. register your app on

3. replace appID in plist file. FacebookAppID and in CFBundleURLTypes

4. #import “DEFacebookComposeViewController.h”

5. use this code for posting

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 DEFacebookComposeViewControllerCompletionHandler completionHandler = ^(DEFacebookComposeViewControllerResult result) {
        switch (result) {
            case DEFacebookComposeViewControllerResultCancelled:
                NSLog(@"Facebook Result: Cancelled");
                break;
            case DEFacebookComposeViewControllerResultDone:
                NSLog(@"Facebook Result: Sent");
                break;
        }
       
        [self dismissModalViewControllerAnimated:YES];
    };
   
    DEFacebookComposeViewController *facebookViewComposer = [[DEFacebookComposeViewController alloc] init];
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [facebookViewComposer setInitialText:@"Look on this"];
    [facebookViewComposer addImage:[UIImage imageNamed:@"1.jpg"]];
    facebookViewComposer.completionHandler = completionHandler;
    [self presentViewController:facebookViewComposer animated:YES completion:^{ }];

Posted in iOS, iPad, iPhone
Tagged DETweetComposeViewController, Facebook, iOS 4, iOS 6, MVC, , SDK

NSTableView with custom header

Default header looks like this

First we want change height of header:

1
2
NSTableHeaderView *tableHeaderView = [[NSTableHeaderView alloc] initWithFrame:NSMakeRect(0, 0, 120, 60)];
    [_tableView setHeaderView:tableHeaderView];

Next step we want change NSTableHeaderCell, can make category for this class or make subclass. So, I wrote category.

Empty category

Continue reading

ScrollView with scroll’s indicators, which are shown all the time.

UPDATE: This solution could cause some issues on iOS 7. For more detail look .

My simple solution by writing category for UIImageView, because scroller is imageview.

How to use :)
Just setup tag for your scrollview and you will get one with scroll indicators, which are shown all the time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#define noDisableVerticalScrollTag 836913
#define noDisableHorizontalScrollTag 836914

@implementation UIImageView (ForScrollView)

- (void) setAlpha:(float)alpha {
   
    if (self.superview.tag == noDisableVerticalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleLeftMargin) {
            if (self.frame.size.width < 10 && self.frame.size.height > self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.height < sc.contentSize.height) {
                    return;
                }
            }
        }
    }
   
    if (self.superview.tag == noDisableHorizontalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleTopMargin) {
            if (self.frame.size.height < 10 && self.frame.size.height < self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.width < sc.contentSize.width) {
                    return;
                }
            }
        }
    }
   
    [super setAlpha:alpha];
}
@end

If you want both scroll it’s easy to change code.

NSRegularExpression sample for comment syntax highlighting

I have this text:

1
word1 word2 " word3 //" word4

I wrote simple solution. I know it can be better. I know about Back Reference, but i don’t have experience with it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"((@\"|\").*?(\"))"
                                          options:NSRegularExpressionDotMatchesLineSeparators
                                            error:nil];
NSArray *textArray = [expression matchesInString:textString options:0 range:NSMakeRange(0, [textString length])];

for (NSTextCheckingResult *result in textArray) {
    // set color for range
}


// Comments
expression = [NSRegularExpression regularExpressionWithPattern:@"(//[^\"\n]*)"
                                                options:0
                                                error:nil];

NSArray * arrayComments = [expression matchesInString:textString options:0 range:NSMakeRange(0, [textString length])];

for (NSTextCheckingResult *resultComment in arrayComments) {

    BOOL inside = NO;
    for (NSTextCheckingResult *resultText in textArray) {
        NSInteger from = resultText.range.location;
        NSInteger to = resultText.range.location+resultText.range.length;
        NSInteger now = resultComment.range.location;
        if (from < now && now < to) {
            inside = YES;
            break;
        }
    }
    if (!inside) {
        // set color for range
    }
}

DDProgressView – Custom Progress View

DDProgressView is a custom progress view à la Twitter for iPhone.

DDProgressView works on both iOS and Mac OS. You must also compile the AppKitCompatibility.m file when targeting Mac OS.

Thanks, Damien DeVille!

Color Picker for iOS

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    // Do any additional setup after loading the view, typically from a nib.
   
    if (self.cPicker == nil) {
        [self.view setBackgroundColor:[UIColor grayColor]];
        self.cPicker = [[VBColorPicker alloc] initWithFrame:CGRectMake(0, 0, 202, 202)];
        [_cPicker setCenter:self.view.center];
        [self.view addSubview:_cPicker];
        [_cPicker setDelegate:self];
        [_cPicker showPicker];
       
        // set default YES!
        [_cPicker setHideAfterSelection:NO];
    }
     
}

// set color from picker
- (void) pickedColor:(UIColor *)color {
    [_rect setBackgroundColor:color];
    [_cPicker hidePicker];
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if (![_cPicker isHidden]) {
        [_cPicker hidePicker];
    }
}

// show picker by double touch
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
   
    if (touch.tapCount == 2) {
        [_cPicker setCenter:[touch locationInView:self.view]];
        [_cPicker showPicker];
    }
}

Get Geo tags from image

Little application for getting geo location from photo

Continue reading

Основы Grand Central Dispatch

В предыдущих статьях писал, что хотел перевести одну интересную статью с английского, но вот нашел перевод  хорошей статьи на русский. Думаю автор перевода не будет против если я копию возьму себе :)

Что это?

Grand Central Dispatch, или, ко­рот­ко, GCD — это низ­ко­уров­не­вое API, ко­то­рая от­кры­ва­ет но­вый спо­соб ра­бо­тать с па­рал­лель­ны­ми (ори­ги­наль­но это concurrent, а не parallel, я не знаю нор­маль­но­го пе­ре­во­да, ес­ли кто ска­жет — на­пи­ши­те в ком­мен­та­ри­ях, прим. пер.) про­грам­ма­ми. На са­мом про­стом уровне по­ни­ма­ния, ме­то­до­ло­гия по­хо­жа на NSOperationQueue, ко­то­рая поз­во­ля­ет раз­би­вать про­грам­му на неза­ви­си­мые за­да­чи, ко­то­рые за­пус­кать па­рал­лель­но или по­сле­до­ва­тель­но. GCD ра­бо­та­ет на бо­лее низ­ком уровне, предо­став­ля­ет боль­шую про­из­во­ди­тель­ность и не яв­ля­ет­ся ча­стью Cocoa.

В до­пол­не­ние к сред­ствам па­рал­лель­но­го вы­пол­не­ния ко­да, GCD та­к­же предо­став­ля­ет пол­но­стью ин­те­гри­ро­ван­ную си­сте­му об­ра­бот­ки со­бы­тий. Об­ра­бот­чи­ки мо­гут быть скон­фи­гу­ри­ро­ва­ны та­ким об­ра­зом, что­бы ре­а­ги­ро­вать на со­бы­тия от фай­ло­вых де­скрип­то­ров, си­стем­ных пор­тов и про­цес­сов, тай­ме­ров и сиг­на­лов, и на поль­зо­ва­тель­ские со­бы­тия. Эти об­ра­бот­чи­ки ис­пол­ня­ют­ся па­рал­лель­но при по­мо­щи ин­фра­струк­ту­ры GCD.

API GCD пол­но­стью ос­но­ван на так на­зы­ва­е­мых бло­ках, о ко­то­рых я го­во­рил в преды­ду­щих се­ри­ях от­ве­тов на во­про­сы («Поз­воль­те пред­ста­вить»: бло­ки и «Об­суж­де­ние прак­ти­че­ских ас­пек­тов ис­поль­зо­ва­ния бло­ков в обыч­ном ко­де»). GCD мож­но ис­поль­зо­вать и без бло­ков, при­ме­няя тра­ди­ци­он­ные C-​шные ме­ха­низ­мы ука­за­те­лей на функ­ции и кон­тек­ста, но ис­поль­зо­вать бло­ки го­раз­до про­ще и неве­ро­ят­но удоб­нее с прак­ти­че­ской точ­ки зре­ния.

Для по­лу­че­ния си­стем­ной до­ку­мен­та­ции по GCD, мож­но на­брать man dispatch в ко­манд­ной стро­ке, ес­ли у вас Snow Leopard. Continue reading

1 2 3 4 Next »