Virtualenv with sudo

Virtualenv is a great way to manage Python environments. Today I ran into an issue when I had to run the script parts of which required sudo privileges and the rest of it needed all my virtual environment packages. When we run sudo all virtualenv settings (environment variables, aliases, functions, etc) become unavailable.
Virtualenv user guide offers following solution:

activate_this = '/path/to/env/bin/'
execfile(activate_this, dict(__file__=activate_this))

Adding this lines to my script saved me a lot of trouble – now I have my environment available when I run sudo!

Use dynamic user variable with XCODEBUILD

Sometimes we need to do something unusual. For example, configure Xcode project so that it could take command line arguments and use them. Sounds simple enough? Let’s see how it works…(the sample project is here)
To be able to use user defined variable, we need to add it to the project. There are some steps to be completed:
1) Define our variable as preprocessor macros, so it is handled when the build operation is performed:
Select target -> Build settings -> Preprocessing -> Preprocessor Macros and add our variable called LABEL_TEXT for debug and release configurations:

Add User Defined Variable
Add User Defined Variable

2) Now we add user-defined setting and give this User-Defined variable the name LABEL_TEXT and a default value – a string “Jupiter” (as the largest planet in Solar system):

Add User Defined Setting
Add User Defined Setting

3) To be able to access this variable from our app, we need a reference to it. We add a keyLABEL_TEXT to Info.plist and set it to value of our user variable: $(LABEL_TEXT)
Now we can access LABEL_TEXT variable by searching for it’s value in Info.plist. If we build and run sample project using Xcode SDK, we’ll see the label with the name of the largest planed in the Solar system.

Now we jump to the main part – passing a user-defined variable from command line tools. In terminal navigate to project folder (the one, which contains .xcodeproj file). Run the following line:

xcodebuild -sdk iphonesimulator8.4 LABEL_TEXT="Mercury" clean build

it tells Xcode command line tool that we need to build for simulator architecture and clean before the build. Also it passes a new argument to our variable LABEL_TEXT. When the build process is completed, we will see the folder named “build” in our project folder, which, in turn, contains the folder Release-iphonesimucator. Navigate to it, make sure your simulator is open, then run:

xcrun simctl install booted

(in case of sample project, that will be xcrun simctl install booted
This will install the app into your simulator.
Now we can go to the simulator, press app icon and observe the effect of user-defined variable. Instead of showing the name of the largest planed in Solar system, the label now shows the name of the smallest planet!

Simple as that, we build the app we can run in simulator using the command-line arguments!

iOS8 and custom UIViewControllers transitions

Currently there is a but in iOS8 custom transitions. When the custom transition is complete, i.e. [transitionContext completeTransition: YES] is called, UIWindow shows empty with no view hierarchy at all. That is seen as a black screen which is appearing instead of destination view controller’s view.
The workaround is to add all views back:

[[UIApplication sharedApplication].keyWindow addSubview:  [destinationViewController].view];

Clean solution for now, probably will be fixed soon)

UIKit Animation

Recently I had a chance to get “Learn iPad development and advanced iOS programming” from Equonix Learning Solutions and wanted to share what I have learned about UIKit animations.

UIKit offers several animation properties for UIViews, for more extensive animations it is better to use Core Animation.

Properties which can be animated using UIKit:

  • frame – size and position
  • bounds – size
  • center – position
  • transform – rotation relative to center point
  • alpha – transparency
  • backgroundColor
  • contentStretch – how content fills the available space

UIKit animation is block-based, i.e. animations are passed as blocks to its methods:

+animateWithDuration: animations:
+animateWithDuration: animations: completion:
+animateWithDuration: delay: options: animations: completion:

These are class methods on UIView, so they can be called on several views.
The options: parameter can control:

  • the animation timing curve
  • the number of repetitions
  • whether the animation reverses
  • whether views get touch events during animation
  • whether animation should wait for any other animation to start

Completion: blocks can be used to chain animation together.

Pascal triangle in Xcode console

Pascal triangle is one of the most famous recursive problems. It has a simple and elegant implementation in Objective-C as well as in many other languages. It turned out, that formatting the output seems more challenging than actual calculation for triangle elements:

+(NSInteger)pascalTriangleForRow: (NSInteger)row Column: (NSInteger)column
     if (row == column || column == 0) {
     return 1;
     } else {
     return [self pascalTriangleForRow:row-1 Column:column-1] + [self pascalTriangleForRow:row-1 Column:column];
     NSMutableArray *triangle = [NSMutableArray new]; 
     for (NSInteger row = 0; row < 10; row ++) { 
         NSMutableArray *currentRow = [NSMutableArray new]; 
         for (NSInteger column = 0; column <= row; column++) { 
             [currentRow addObject:@([self pascalTriangleForRow:row Column:column])]; 
         NSString *rowAsString = [currentRow componentsJoinedByString:@" "];
         [triangle addObject:rowAsString]; 
      NSString *triangleString = [triangle componentsJoinedByString:@"\n"]; 
      NSLog(@"\n%@", triangleString);

Insertion sort

Insertion sort is a simple sorting algorithm:

    for (NSInteger index = 1; index < [array count]; index++) {
        NSInteger currentValue = [array[index] integerValue];
        NSInteger position = index;
        while (position > 0 && ([array[position -1] integerValue] > currentValue 
             array[position] = array[position-1];
             position = position-1;
       array[position] = @(currentValue);
       return steps;


Warning: performSelector may cause a leak because its selector is unknown

Complains about:
[someObject performSelector:NSSelectorFromString(@”someMethod”)];

Reason: with ARC the runtime needs to know what to do with the result of the method we are calling. The result can be anything: void, int, char, NSString, id etc. Usually this information is contained in header of the object type we are working with.
What ARC can do with the return value?

  • ignore non-object types (void, int etc)
  • retain object value, then release when it is not used anymore
  • do nothing, assume that return object value will be valid in local scope

The call to methodForSelector: assumes that the return value of the method is an object, but does not retain/release it. So, if the object is supposed to be released, there can be a memory leak.

What if return value is void?
From the compiler perspective it is still an object, so it gives us warning to prevent garbage pointer value being retained/released and crash of an app.

How to fix?

  • static selectors

[_controller performSelector:@selector(someMethod)];
here compiler is able to record all information about the object during compilation and doesn’t need to make assumptions

  • delay execution

[self performSelector:aSelector withObject:nil afterDelay:0.0];
used when acceptable (return object is void and there is no problem to let the runloop cycle once), removes warning by reassuring the compiler that no object can be returned and mismanaged

  • suppress warning

#pragma clang diagnostic ignored “-Warc-performSelector-leaks”
for one line, in case of the whole project macros can be used
Suppressing warnings is ambiguous and not welcomed by many programmers

Change annotation view for state of annotation on MapView

Imagine that we need to change color of custom annotationView, when an annotation has been selected.
Our steps:

  • retrieve the annotation’s current view using the MKMapView instance method viewForAnnotation (the catch here is that it is not the same as mapView:viewForAnnotation: delegate method)
  • modify properties of current view
for (MyAnnotation *selectedAnotation in selectedAnnotations) 
    MKAnnotationView *selectedAnnotationView =[self.mapView viewForAnnotation:selectedAnotation];
    selectedAnnotationView.image = newImage;

Concurrency and NSOperation

Multithreading implementations vary a lot, from low-level APIs (like POSIX pthread) to very high-level, which are built on top of low=level and they are friendlier and easier to use. In this respect, NSOperation is higher than GCD, which still has a lot of complexity.

What is what?

  • Thread – a unit of execution, generally expected to share memory and other resources with other threads and managed independently by operating system scheduler. Every UI code runs on main thread.
  • Process – instance of program that is being executed. One process can have one or many threads.
  • Concurrent operation – takes place in a different thread than the one it was started in.
  • Condition – will prevent thread from processing if not met. Used for synchronisation purposes.
  • Critical section – piece of code that access shared resource that must not be accessed by more than one thread.
  • Mutex – “lock”, requirement to ensure that no two concurrent threads are in their critical section at the same time. Mutexes and conditions are examples of Semaphore – protected variable that restricts access to a shared resource.


Operation objects are instances of NSOperation and they encapsulate code that we want to perform. To use NSOperation, we must subclass it. There are two subclasses available, and being used most of the time. For special cases, we can create our own subclasses.
NSInvocationOperation – instantiated by using already existing object and selector from an application.
NSBlockOperation – can use this class to execute various block objects at once.

Features of operation objects:

  • Dependencies – can make an operation execute after another one had finished.
  • Optional completion blocks
  • Prioritizing tasks
  • Any operation can be cancelled at any time
  • Operations commonly are executed by adding them to queue.

Representational State Transfer

REST (Representational State Transfer) is an architecture style for designing network applications. It was introduced and defined in 2000 by Roy Fielding in his doctoral dissertation. Unlike complex mechanisms (For example, Remote Procedure Calls (RPC) where the calling arguments are passed to the remote procedure and the caller waits for a response to be returned from the remote procedure), it uses HTTP to connect between machines.
HTTP is the underlying protocol of World Wide Web. It defines how messages are formatted and transmitted, and what actions web servers and browsers should take in response to various commands.

  • HTTP is stateless, i.e each command executed independently, without any knowledge of the commands that came before it.
  • HTTP is client-server protocol, which treats this two part separately. Client sends request to Web server, which is responsible for document storage and retrieval, it sends the information back.
  • HTTP is cachable, i.e. it allows the client side to cache information and has specifications for when a response can be cached. In this protocol caching is desirable so it’s explicitly designed for it.
RESTful example
RESTful example

RESTful applications use HTTP requests to post data (create and update), read data (make queries) and delete data.
Key components of REST architecture:

  • Resources – identified by URLs
  • A web of resources – a single resource should not be too large and contain too fine-grained details. Instead, the resource should contain links to additional information.
  • Client-server, where one component’s server can be another component’s client
  • No connection state, each request must carry all information required to complete it, and must not rely on previous interactions with client
  • Resources should be cachable when possible, to allow server to specify which resources may be cached and for how long HTTP cache-control headers are used.
  • Proxy servers (intermediary servers) can be used to improve performance.