Blog

  • Reload UITableView cells

    Sometimes it’s needed to reload only some of the rows of UITableView to save some time and energy and not reload whole the table. This is how it can be done:

    NSIndexPath * indexPath = \
       [NSIndexPath indexPathForRow:row inSection:0]; 
    [self.tableView reloadRowsAtIndexPaths: \
       [NSArray arrayWithObject:indexPath] \
       withRowAnimation:UITableViewRowAnimationMiddle];
    
  • Save current position in UIScrollView and then scroll to this position

    To save a position of the current scroll view use this method:

    - (void)savePosition {
        positionY = webView.scrollView.contentOffset.y;
        NSLog(@"positionY:%d", positionY);
    }
    

    To scroll programmatically to the saved position use this method:

    - (void)scrollToYPosition:(int)positionY {
        [self.webView.scrollView setContentOffset: \
    CGPointMake(self.webView.scrollView.contentOffset.x, positionY)];
    }
    
  • How to build MailCore framework on iOS

    MailCore is a Cocoa e-mail framework built by Matt Ronge that is the core of the e-mail client Kiwi. MailCore provides a nice set of objects for working with IMAP, MIME and SMTP, all of which use the C e-mail library LibEtPan. Here is some short information about MailCore. This is short documentation on MailCore from Matt Ronge. Official website is here.

    To make it run on your iOS simulator, do the following:

    1. Download MailCore from GitHub:
      git clone https://github.com/mronge/MailCore.git
      cd MailCore/
      git submodule init
      git submodule update
      
    2. Build m4, autoconf, automake, libtool on Mac OS X Lion using this post.
    3. Run update.sh script in MailCore to build and install everything before opening it in Xcode. If you don’t know, how to run shell scripts, read this
    4. Open MessageSender project in MailCore library. Select MessageSender to build. It will not do anything. To make it sending a test message write the following code in ViewDidLoad:
      CTCoreMessage myMessage = [[CTCoreMessage alloc] init];
          
      // Set To
      CTCoreAddress *addrTo1 = [CTCoreAddress address];
      [addrTo1 setEmail:@"Your E-mail1"];
      CTCoreAddress *addrTo2 = [CTCoreAddress address];
      [addrTo2 setEmail:@"E-mail2"];
      /*CTCoreAddress *addrTo3 = [CTCoreAddress address];
      [addrTo3 setEmail:@"E-mail3"];*/
      [myMessage setTo:[NSSet setWithObjects:addrTo1, addrTo2, nil]];
        
      // Set From 
      CTCoreAddress *addrFrom = [CTCoreAddress address];
      [addrFrom setEmail:@"Your E-mail"];
      [addrFrom setName:@"Your Name"];
      [myMessage setFrom:[NSSet setWithObject:addrFrom]];
         
      [myMessage setSubject:@"Test Mail Core"];
      [myMessage setHTMLBody:@"This is a test HTML message"];
         
      [CTSMTPConnection sendMessage:myMessage \
      server:@"smtp.mail.ru" username:@"YourUserName" \
      password:@"YourPassword" port:587 useTLS:YES useAuth:YES];
      
    5. Use this method to retrieve message subjects from Inbox of your mail:

      - (IBAction)retrieveClicked:(id)sender {
          CTCoreAccount *account = [[CTCoreAccount alloc] init];
          [account connectToServer:@"imap.yandex.ru" port:143 \
       connectionType:CONNECTION_TYPE_PLAIN authType:IMAP_AUTH_TYPE_PLAIN \
       login:@"YOUR USERNAME" password:@"YOUR PASSWORD"];
          
          NSSet *subFolders = [account subscribedFolders];
          
          CTCoreFolder *inbox = [account folderWithPath:@"INBOX"];
          
          NSSet *messageList = [inbox messageObjectsFromIndex:1 \
       toIndex:0];
          
          for (CTCoreMessage *message in messageList) {
              NSLog(@"%@", [message subject]);
          }
      }
      

    Official MailCore website.

  • What’s new in iOS 6: developer-related features

    This is the link for Apple Developers.

    Brief content (developer-related features):

    iOS 6.0

    Maps
    In addition to the new map tiles provided by Apple, the Maps app and MapKit framework now support additional interactions with other apps.

    Social Framework
    The Social framework (Social.framework) provides a simple interface for accessing the user’s social media accounts.

    Pass Kit
    Pass Kit is a new technology that uses web services, a new file format, and an Objective-C framework (PassKit.framework) to implement support for downloadable passes.

    Game Center
    Game Center has been updated and new features have been added to improve the game playing experience.

    Reminders
    The Event Kit framework now includes interfaces for creating and accessing reminders on the user’s device.

    In-App Purchase
    The Store Kit framework (StoreKit.framework) now supports the purchasing of iTunes content inside your app and provides support for having downloadable content hosted on Apple servers

    Collection Views
    The UICollectionView class offers a new way to present ordered data to users. With a collection view object, you are now able to define the presentation and arrangement of embedded views

    UI State Preservation
    State preservation makes it easier for apps to restore their user interface to the state it was in when the user last used it.

    Auto Layout
    Auto layout improves upon the “springs and struts” model previously used to lay out the elements of a user interface. With auto layout, you define rules for how to lay out the elements in your user interface.

    Data Privacy
    In addition to location data, the system now asks the user’s permission before allowing third-party apps to access certain user data

    Additional Framework Enhancements

  • Как закрыть Терминал из командной строки

    Закрыть его можно, но это сложно. Проще нажать Cmd+Q :

    $ osascript -e 'tell application "Terminal" to quit'
    
  • Добавление и переход на номер строки в Vim

    Чтобы добавить номер строки в редакторе Vim, напишите следующее:

    :set number (or nu)
    

    перед тем как зайти в режим редактирования. (там же, где пишете :wq, чтобы выйти)

    Чтобы сразу перейти к определенной строке (с ошибкой, например), напишите:

    vim +31 Hello_world.pl
    

    Здесь 31 – номер строки, Hello_world.pl – редактируемый файл (Perl)

  • Delete files by mask in Bash (Terminal)

    Go to the folder, where you want to delete for instance all mp3 files in this folder and it’s subfolders and type this:

    $ for i in $( find . -name "*.mp3" ); do rm -f $i; done  
    

    If you want to delete files by mask only in current folder, type this:

    $ rm -rf *.mp3
    
  • Creating Local SVN Repository for Project

    1.

    $ svnadmin create RepositoryName
    

    2. While in the project folder:

    $ svn import
     "file:///Users/user/RepositoryName/" -m "Initial import"
    

    3. Create a project folder:

    $ mkdir "~/Users/user/Documents/ProjectFolder"
    

    4. Go to the documents folder:

    $ cd "~/Users/user/Documents/"
    

    5. Check out from repository:

    $ svn checkout "file:///Users/user/RepositoryName/" ProjectFolder
    
  • Паттерны проектирования

    Заметки при чтении книги “Паттерны проектирования” (Эрик и Элизабет Фримен)

    ——————————————————————————————————-

    Examples Source Code: GitHub

    Паттерн Стратегия определяет семейство алгоритмов, инкапсулирует каждый из них и обеспечивает их взаимозаменяемость. Он позволяет модифицировать алгоритмы независимо от их использования на стороне клиента.

    Скачайте примеры кода на Java c GitHub.

    ——————————————————————————————————-

  • Мои заметки после работы с VBA (Tips and tricks)

    Конвертация из String в Integer:

     i = CInt(s)
    

    Конвертация из Integer в String:

    s = str(i)
    

    Активация конкретного листа:

    sheets("mytabname").activate
    

    Использование циклов Do и выход из циклов:

    
    Do [{While | Until} condition]
    [statements]
    [Exit Do]
    [statements]
    Loop
    
    Or, you can use this syntax:
    Do
    [statements]
    [Exit Do]
    [statements]
    Loop [{While | Until} condition]
    

    Процедура для удаления пустых строк

    Private Sub CommandButton3_Click()
    'Delete empty lines
    
    Dim numberOfRows, count As Integer
    Dim sheetName As String
    
    sheetName = TextBox3.Text
    Sheets(sheetName).Activate
    
    numberOfRows = CInt(TextBox1.Text)
    count = 0
    
    For i = numberOfRows To 1 Step -1
        If (Cells(i, 1).Value = Empty) Then
            count = count + 1
            Cells(i, 1).EntireRow.Delete
        End If
    Next i
        
    MsgBox ("Finished. Number of deleted rows is" + Str(count))
    
    End Sub
    

    Проверка того, что ячейка пуста и удаление целой строки:

    If (Cells(i, 1).Value = Empty) Then
            count = count + 1
            Cells(i, 1).EntireRow.Delete
    End If
    

    Показ сообщения с числом каким-нибудь:

    MsgBox ("Finished. Number of deleted rows is" + Str(count))
    

    Добавление данных на другой лист:

    Worksheets("XProdRugSets").Cells(i + j - firstRugSetIDRow + 1, 1).Value = ProdID