Programming with GUTs

Blocks in Objective-C

Blocks in Objective-C

Quick overview

Blocks are the closure pattern implementation in Objective-C. Blocks are objects containing code like a method but blocks are standalone objects (not belonging to a specific class/instance) encapsulating and capturing the code and variables enclosed in the beginning and closing brackets.

You declare a block type or variable this way:
returnType (^blockName)(paramType, paramType)

Assign a block to this variable:
    ^ returnType (paramType paramName, paramType paramName) {
… code …
}

Block as a parameter:
(returnValue (^)(paramType, paramType))blockName

Call with a block as parameter:
^ returnType (paramType paramName, paramType paramName) {
… code …
}

Some example

You declare a block variable the following way:

// a block which takes a string and and int as parameter and returns a string
NSString* (^simpleBlockVariable)(NSString*, int) = ^ NSString* (NSString* stringParam, int intParam) {
    return [NSString stringWithFormat:@"stringParam %@, intParam: %d", stringParam, intParam];
};

// you can call it a the following way
NSString* stringResult = simpleBlockVariable(@"Hello", 1);

You can assign a new block to the same variable; you can also avoid the declaration of the return value since the compiler can find it out:

simpleBlockVariable = ^ (NSString* stringParam, int intParam) {
    return [NSString stringWithFormat:@"second version: stringParam %@, intParam: %d", stringParam, intParam];
}

Even you can avoid the parameter declaration so you get the simplest form of a block:

void (^simplestBlockVariable)() = ^ {
    NSLog(@"simplest block called");
};
 
// you call it like this   
simplestBlockVariable();

 

Passing blocks as parameters the syntax change a bit

// a block with two parameters: a string and a block which takes to parameters (string and int) and returns a string
NSString*(^blockVariableWithBlockParameter)(NSString*, NSString*(^)(NSString* , int )) = ^ NSString* (NSString* theString, NSString*(^completion)(NSString* , int )) {
    NSString* aNewString = [NSString stringWithFormat:@"Incoming string: %@", theString];
    NSString* resultString = completion(aNewString, 10);
    return resultString;
};

// you call it the following way    
NSString* theResult = blockVariableWithBlockParameter(@"Hello", ^ NSString* (NSString* stringParam, int intParam) {
    NSString* resultString = [NSString stringWithFormat:@"string from the completion: stringParam: %@, intParam: %d", stringParam, intParam];
    return resultString;
});

// Value of theResult: string from the completion: stringParam: Incoming string: Hello, intParam: 10

 

 

Allocate Swift objects from Objective-C

Using mixed projects you can face with several challenging situations. One of them is the allocation of Swift objects in ObjC code.

The general problem that Swift objects doesn’t have an alloc method which is used to allocate the memory in ObjC ([[SwiftClass alloc] init]).
To access the Swift object you should prefix it with @objc – or subclass from NSObject.

There are several workarounds however:

  • Make the NSObject as base class of the Swift class. As you use mixed project already this seems to be the best solution.
    class YourSwiftClass : NSObject
  • Declare a class (static) method which returns a new instance of the object:
    class func newInstance() -> YourSwiftClass {
        return YourSwiftClass()
    }
  • Implement the alloc method – similar to the previous solution
    class func alloc() -> YourSwiftClass {
        return YourSwiftClass()
    }
  • Use a kind of introspection
    [[NSClassFromString(@"YourProjectName.YourSwiftClass") alloc] init]
  • Declare but not implement a category in the ObjC code where you want to allocate the Swift object – yes, it really works
    @interface YourSwiftClass (allocation)
        + (instancetype)alloc;
    @end

If TextEdit makes your files wrong

From Mavericks  theMAC OS X embedded default text editor tool, the TextEdit uses autocorrection by default so replaces your correct characters to funny ones.
This is getting more funny when you open and edit a JSON file for example. And you won’t realize what went wrong a quite long time 🙂

So, just switch it off:
Apple symbol > System preferences… > Keyboard > Text > Uncheck “Use smart quotes and dashes”
TextEdit > Preferences… > Uncheck “smart quotes” and “smart dashes”
In TextEdit, Edit > Substitutions > Uncheck “Smart Quotes” and “Smart Dashes”

Navigating back and forth among Viewcontrollers in Storyboard

In the old days if you wanted to present a ViewController you should call presentModal.. or push… in the code.  The problem with this approach is that if you want to modify the presentation you should change the code.

To separate this Apple found out the Storyboard – all your ViewControllers in one place. Visually representing the ViewControllers and their relations.
You can control on the Storyboard how different ViewControllers are presented – the code of a ViewController is totally free of how another ViewController is presented. A segue describes what to present (from where to where) and how. You can bind a control’s touchUpInside to a segue for example. If a segue navigates backward it is called unwind segue. You can give them a name and you can fire it manually (from code).
To pass data to a ViewController override the:
 – (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender method.

Unfortunately not everybody knows the unwind segue. This is about to navigate backward in the presentation chain. With unwind segue you can navigate back not only to the previous ViewController but back to any other ViewController in one step! For this you have to create a method in a ViewController you want to navigate back with a special signature:
– (IBAction) unwindToXYZViewController:(UIStoryboardSegue*)segue.

This method can be used to access the data in the presented ViewController.
You should name it properly to know where you want to navigate back. XCode will present you all the unwind segues when you want to bind one – and you have to select a good one 🙂 Just controler+drag from the control to the third button (Exit) on top of the ViewController in storyboard and select the method in the presenting list.

The only big question what Apple did not solved is the multiple unwind segue. Imagine that two ViewController (A and B) presents the same (C) ViewController. Now when you want to create an unwind segue for example pressing a button you can bind only one segue. So how can you navigate back to the proper ViewController?

Below is the answer I figured out.

What you have to do is to create two manual unwind segues. One for each ViewController you want to navigate back. To do this control+drag from the first button on top of the ViewController to the third one.
Now the tricky part: you have to manually fire the proper segue. For this you have to decide which is the previous ViewController – which one presented the “C” ViewController. Unfortunately Apple don’t provide any simple property or method.

So I created a category method on the UIViewController which gives back the proper one.
Here is the code snippet:
[expand title=”click to show code snippet”]

@implementation UIViewController (HelperMethods)

- (UIViewController*) previousViewController {
    UIViewController *viewControllerToReturn = nil;
    
    // !!!: navigation should have the preference as if a navigation was opened modally and this viewcontroller is the third pushed then the presenting will be the one opened the modal
    if (self.navigationController!=nil)
    {
        NSUInteger index = [self.navigationController.viewControllers indexOfObject:self];
        if (index > 0)
        {
            --index;
            viewControllerToReturn = self.navigationController.viewControllers[index];
        }
        else if (index == 0) // if this is the root in the navigation return the modal presenter of the navigation
        {
            // to be sure check the instances...
            if (self.presentingViewController.presentedViewController == self.navigationController)
            {
                viewControllerToReturn = self.presentingViewController;
            }
        }
        // else NSNotFound. what the hell?
    }
    else if (self.presentingViewController.presentedViewController == self) // make sure this viewcontroller is the modally presented one
    {
        viewControllerToReturn = self.presentingViewController;
    }
    
    // TODO: handle other controllers: Tab Bar, Page etc,
    
    return viewControllerToReturn;
}

@end

[/expand]

Now to fire the proper unwind segue:

UIViewController* previousViewController = [self previousViewController];
    
if ([previousViewController isKindOfClass:[AViewcontroller class]]) {
    [self performSegueWithIdentifier:@"UnwindToAViewControllerSegueId" sender:self];
}
else if ([previousViewController isKindOfClass:[BViewController class]]) {
    [self performSegueWithIdentifier:@"UnwindToBViewControllerSegueId" sender:self];
}

The nice in it that you can freely change the presentation of the ViewControllers

Coding Guidelines

General

The main reason of this document is to help to achieve a clean code, which is:

  • Readable: easily understandable – by other developers
  • Maintainable: easily changeable by other developers as well
  • Flexible: can be extended and add new functionality
  • Testable: can be unit testable – where other classes are mocked even if the classes are the part of the component or not. The test should cover at least a positive and a negative flow where the mock objects provide different results.

Design/architecture

  • One file – one class: it is very confusing if a file contains different classes. The project structure should mirror the class structure.
  • One class – one responsibility: each class has to have one specific concern. Do not create huge classes, which performs different tasks and stores different states.
  • Keep the class size fewer than 600 lines. If the lines exceed the limit it probably means the class performs to many tasks and should separate to more classes.
  • One method – one task: one simple task should be performed by a method
  • Keep the method size less than 60 lines or one screen size. Preferable is less. Much easier to overview a smaller method. Moving code to smaller methods makes the original method more readable, especially if you use descriptive names – and you should. The smaller methods are more reusable and maintainable as well and changing them can introduce fewer errors.
  • Different modules should not be referenced directly even if the module is part of the code or a third-party library. Direct references make harder (or impossible) the proper unit testing and also the possibility to vary the classes later. Declaring a clear minimumprotocol also helps the proper planning. If a module contains more classes the classes can depend on each other of course.
  • Accessing different modules: keep reference only to the objects you really have to.
  1. Use parameters: the most easier to test and provides the clearest architecture also the most understandable approach.
  2. Use properties to set the dependent instances.
  3. Use a public dedicated class (service locator), which provides the required instances (dedicated methods provide the instances of singletons or can behave like factories).
  4. Use singletons only if you’re don’t have any other option.

Naming

  • Use self-descriptive names. The name should suggest what the method does. Good names can institute simple comments. Avoid shortenings. Always think of the mind of a developer who doesn’t work on the project: will he/she understand what is that method/variable? What it does?
  • File names should be the same as the class names. Remember: one file, one class.

Coding

  • Keep the code clean (apply the guideline): don’t hesitate to change a code snippet when you change or add something if you see the result is not clear. Leaving small dirty code snippets results in an unmaintainable code.
  • Avoid code duplication: if the same code snippet should be copied to somewhere else always make a new method instead and call that from both parts. The code will be more readable, understandable, maintainable and smaller.
  • Separate queries (getters) from modifiers (setters). Always be clear what a method does: modifies the state of the class or retrieves a value. Do not mix them!
  • Do not use more than two (three) parameters for methods. If you really need more, consider passing a dedicated parameter object instead or use properties to set the desired values.
    Other option is to change the logic of that part of the code as these kinds of problem suggest there is too much to do.
  • Do not embed different method calls in each other. Limit it to one call for a parameter.
    Long lines mean something is wrong with the code. Setting local variables and passing them to the call make the code much clearer and easier to debug.
  • Do not use string literals or constant number values in the code. Use named constants instead. The constant numbers do not say too much about the purpose of the values but their names can do. This way all the key constants will be in one place so the changes are simpler and the readers of the code also have an overview of the magic numbers in the code.
    • use const strings instead of string literals: helps debugging as well
    • use enums, consts for constant numbers
    • Do not call long running operations from main thread. They will block the main thread where the user interaction happen and the application will seems to unresponsive sluggish.
      Network calls should run always on background thread.
    • Do not use exceptions to signal simple errors (especially from init methods): exceptions are for critical and/or developer errors. Return some default value (NULL/nil) or provide a returning error parameter.
    • Call property getter/setter accessors instead of access ivars directly. One can modify later the getter/setter to add additional logic or implement different behavior (for example lazy-binding, logging or debugging).

Comments

There are two types of comments regarding the target:

  • Public comments for the user who want to use the class: describe what the method does. Should be in the header file. Usually doxygen compatible comments should be used (for reference see: http://www.stack.nl/~dimitri/doxygen/docblocks.html)
  • Private comments for other developers who work on the code: describe how the method works. Always think you explain the code.
    Should be in the implementation file and use regular commenting

For comments keep in mind the following basic rules:

  • Place a file header comment in each file; the structure and look should be declared by the project.
    Usually the header contains the component/class name, author, company and other general information
  • Comment the class: give a clear description about the main concern of the class. If necessary describe how the class should be used even with code snippets if necessary
  • Comment each method/property
  • Use the single-line comment (//) in the code instead of multiple line comments (/* */).
  • For readability reason add a space after the comment sign: // a comment
  • Do not add doxygen like comments inside methods – these won’t be extracted and won’t appear in the generated documentation!
  • Do not leave commented code snippets in the code in long term. If it really needed to let the code in, describe why was it commented out, when can one uncomment it.
    Commented code blocks are meaningless and nobody knows after a time why that code was there or was commented out. Usually nobody will use that code part any more.

Spacing and Formatting

Can vary between projects but must be uniform in one project. Good practice to use the default formatting of the IDE/language.

 

iOS

General

Apple provides a clear documentation and guideline about coding: Coding Guidelines for Cocoa at https://developer.apple.com/library/mac/ – documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html.

As the apple guideline describes all aspects in a detailed way this document contains only the most frequent issues found in the existing code or where clarification was necessary.

In some circumstances it is possible to avoid some of these rules but always discuss it with the team lead.

Naming

  • Usually unnecessary to explicitly declare iVars (instance variable, a member) for properties, the compiler automatically creates them for you. Using the latest XCode you don’t have to specify the @sythesizes so the code will be more compact.
    The usage suggest you what is used: ‘self.myIvar’ a property, while an iVar (without the ‘self.’) would be ‘myIvar’ (@synthesize was used) or ‘_myIvar’ (@synthesize wasn’t used).
    If you really need an ivar for a property there is usually also a reason to distinguish the ivar name with a prefix or postfix.
  • Do not use and in method names for parameters, except if the method performs different actions (so the actions are delimited by the and, not the parameters):
    wrong: – (int)runModalForDirectory:(NSString *)path andFile:(NSString*)name andTypes:(NSArray *)fileTypes;
    better: – (int)runModalForDirectory:(NSString *)path file:(NSString *)name types:(NSArray *)fileTypes;
    different actions: – (BOOL)openFile:(NSString *)fullPath withApplication:(NSString *)appName andDeactivate:(BOOL)flag;
  • Do not use get in getter accessor names.
  • Class names and global shared constants should start with a short prefix, which is a unique abbreviation of the project or module, substituting namespaces what are missing in ObjC.
    For example: MAFLogonManager – Mobile Application Framework Logon Manager
  • File names should be the same as the class name except in case of categories. Category file names should start with the original class name followed by a ‘+’ sign and the name of the category. For example: NSString (Additions) category should be in a file named NSString+Additions
  • For singletons use the shared or default method name prefix for methods which provides the instance of the class
  • For parameter (and local variable) names use a prefix: aParam, anObject, theObject.
    This marks that the variable is temporary. Useful further if the parameter would have the same name as an ivar or property.

Coding

  • There must be at least one designated initializer, which calls the designated initXXX method of the superclass. The designated initializer must be the method with the most parameters. Always override the original designated initializers when you make a new subclass (introducing a new of overriding an existing initializer) to make sure your initializers will run and your class will be initialized properly.
    Good practice to call the designated initializer from other initializers in the same class.
  • Set the IBOutlet properties to nil in viewDidUnload to release the resources. The XCode generates the code for you this way (for example if you add a new referencing outlet).
  • Do not call accessors (setting to nil a property) from dealloc and always consider calling it from init…. Call release in dealloc and set the ivar directly in init.
    Subclasses can be already in invalid state (deallocated all iVars) when dealloc method of the super executes, making accessor methods potentially unreliable.
    A setter method may be doing more things than simply releasing the property. It also sends out KVO notifications automatically even if you implement the setter/getter manually. Even if you’re not implementing the setter yourself, a subclass might. In all cases it is not a good idea to run the related code from dealloc.
    Note: XCode generates the code for you this way for example if you add a new referencing outlet through interface builder.
  • Do not call release on the result of a property getter even if it was called on self.
  • Put private ivars in the implementation file.
    The header file is published like a protocol. The user of the object doesn’t have to know the inner structure of the class.
    @implementation MyViewController {
    int myIntIVar;
    }
  • Do not put private method and property declarations into the public header file. It makes the class structure unnecessarily complex and dangerous if someone starts to use them. Put them into a class extension instead (the compiler doesn’t force to declare private methods!).
    @interface MyViewController ()
    @property (nonatomic, copy) NSString *myPrivateProperty;
    @end
  •  Use the AppDelegate only for application level operations and events. Put other code to specific classes and ViewControllers. Keep the AppDelegate clean (refers to one class-one concern).

Common errors

  • Always consider the proper usage of property attributes.
    A property to an immutable class can always get a mutable instance. Use copy (instead of retain) if you want to make sure the data won’t change after the property was set. Mainly with strings and arrays.
  • For button taps use TouchUpInside instead of touchDown or other touches except if that is the requirement.
  • Don’t forget to implement viewDidUnload if you have viewDidLoad.
    If there is a memory warning the system releases the hidden views and calls viewDidUnload. When the view will appear again the system loads the view again and calls viewDidLoad. Without a viewDidUnLoad the application will leak.
  • Use the dot notation only for properties. Do not use them for parameterless methods.

Comments

  • Use #pragma mark to visually partition code, and add a short, meaningful description to the given block
    #pragma mark – Public method implementations
  • Use !!!, ???, TODO or FIXME in comments if you want to highlight something but don’t let them in for a long period.
  • In some cases you can use #warning or even #error in your code to signal special cases or avoid wrong usage of the code. Usually these are used in an #if or #ifdef condition.
  • If the project uses other libraries always cross-references them even if there must be a project, which uses the precompiled libraries.
    Cross-referenced libraries are easier to debug and the development of the libraries are also easier.
  • Using cross-referenced libraries all the bundles and used files should be referenced from the referenced projects (instead of using the built/maven version).
    Modifying the file (for example an xml in the bundle of the referenced library) will be visible right after the modification. Otherwise the library should be submitted to the repository wait for the build and update the files using maven or other tool.

Project settings

  • If the project uses other libraries always cross-references them even if there must be a project, which uses the precompiled libraries.
    Cross-referenced libraries are easier to debug and the development of the libraries are also easier.
  • Using cross-referenced libraries all the bundles and used files should be referenced from the referenced projects (instead of using the built/maven version).
    Modifying the file (for example an xml in the bundle of the referenced library) will be visible right after the modification. Otherwise the library should be submitted to the repository wait for the build and update the files using maven or other tool.

Select items from a list without repetition

There are more solutions how to select items from a list randomly

Initial steps:

  • Cycle from 1 to N
  • Select the item at random index,
    add it to the result array
  • Solutions:
    1. if the item is already in the list skip. Drawbacks: your number of iterations could be huge
    2. Remove the item from the original list: not works for large lists or if the item is not in memory; need a linked list otherwise which needs more memory

A better solution is to swap the item at index with an item at a random index – and iterate this from the beginning of the list x times. On finish take the first x items. The drawback is that the list should be in the memory and the items should be changeable. But then you lost the original list. You can do the same on an index array, but again it needs more memory.

So there is a much better solution than the previous ones:
Calculate probability for the items (at once only for one)
Probability= ‘items still needed’ / ‘all items left’.
If the probability is greater than the random number (between 0-1) add it to the result (‘items still needed decrase), else skip.
Decrease ‘all items left’.
For first look it seems a problem that all the items can be skipped but there isn’t any trouble: when ‘items still needed’=’all items left’ then the probability will be one, so all items will be added to the result, and the two counter will decrase together.
This algorithm can be used on items not in memory, no extra memory allocation needed and the items (and their orders) won’t change.

iOS/ObjC Interview Questions

General programming questions

  • OOP basics: what is a class, interface, instance variable, methods, static (class) methods vs instance methods. Header vs implementation files
  • What is a process, thread
  • design patterns and principles
  • blackbox vs whitebox testing differences? unit testing? integration testing? regression testing?
  • what is continuous integration?
  • difference between stack/heap

General ObjC

[expand title=”What do you need to be able to develop for iOS” tag=”div”] MAC OS X, XCode, Developer Profile …[/expand]
[expand title=”Define basic OOP concepts and the keywords in ObjC” tag=”div”] interface, implementation, inheritance, property, protocol, etc… [/expand]
[expand title=”Application lifecycle; What kind of states an application can have? Which general methods are called?” tag=”div”] States: not running, inactive, active, background or suspended. There are methods and notifications to handle the transitions.

  • application:willFinishLaunchingWithOptions:
  • application:didFinishLaunchingWithOptions>:
  • applicationDidBecomeActive:
  • applicationWillResignActive:
  • applicationDidEnterBackground:
  • applicationWillEnterForeground:
  • applicationWillTerminate:
  • applicationDidFinishLaunching:

[/expand]
[expand title=”What is a property? How can you create one? What is the benefits to use properties?” tag=”div”] @property, (auto)synthesize; getter/setter method (also send KVO notifications). Hides the iVars (safety and flexibility) [/expand]
[expand tag=”div” title=”method visibility”] private/public – no protected. anyone can call a private [/expand]
[expand tag=”div” title=”What is a protocol? Protocol declaration and implementation, optional declaration”] [/expand]
[expand tag=”div” title=”How to check an optional protocol method existence on an object? “] [/expand]
[expand tag=”div” title=”+ and – methods”] class vs instance methods [/expand]
[expand tag=”div” title=”What about multiple class inheritance”] technically none … [/expand]
[expand tag=”div” title=”How to add a method to a class (extend) without the source of the class and without recompiling the class”] Categories [/expand]
[expand tag=”div” title=”what are categories?”] [/expand]
[expand tag=”div” title=”Difference between extensions () and (named) categories?”] [/expand]
[expand tag=”div” title=”Benefits of extension category?”] private property declaration, compile time method check. [/expand]
[expand tag=”div” title=”Can you re-declare a property in subclass or extension?”] YES. If you declare a property in one class as readonly, you can redeclare it as readwrite in a class extension, in a protocol, or in a subclass. [/expand]
[expand title=”Limitations of- and problems with categories?”] Cannot override an existing method and call it in the extension method [/expand]
[expand tag=”div” title=”What are formal and informal protocols?”] Formal are the real protocols, informal are categories on NSObject (with optional methods) [/expand]
[expand tag=”div” title=”How to declare protected-like methods (accessible only for some dedicated classes)?”] Separate header file with (named) category, and include it in other class [/expand]
[expand tag=”div” title=”What is a designated initializer, what is the pattern for the initializers and why ( if (self = %{%super …%}% ) )”][/expand]
[expand tag=”div” title=”Property modifiers and the meaning”]nonatomic/atomic, assign/retain/copy/readonly vs strong/weak/unsafe_unretained, getter=, setter=[/expand]
[expand tag=”div” title=”How can one object inform an other that something happened?”]only one (subscribing): target-action, delegate, block. Unlimited: notification[/expand]
[expand tag=”div” title=”What is a delegate, how to create one, and use one”][/expand]
[expand tag=”div”  title=”When to create a delegate”][/expand]
[expand tag=”div” title=”Delegate rule: how to handle ownership and why”]never retain! circular reference problem[/expand]
[expand tag=”div” title=”Delegate vs target/action vs block vs NSNotification”][/expand]
[expand tag=”div” title=”Problem with blocks usage”] recursive calls (on fail restart the method which expects the same block) problematic and only one ‘method’ can be called – delegate can have more methods. Solution to recursive calls: put the method to a __block local variable, so it can call/reference itself[/expand]
[expand tag=”div” title=”What is a selector? How to call a selector?”][/expand]
[expand tag=”div” title=”What is the difference between the dot notation and using the square brackets”][/expand]
[expand tag=”div” title=”What is KVO – where/how/why to use – how does it work – how to implement properly a KVO compliant property”][/expand]
[expand tag=”div” title=”What is KVC – where/how/why to use”][/expand]
[expand tag=”div” title=”What is fast enumeration”][/expand]
[expand tag=”div” title=”check a class is compatible with a baseclass and a given class”]isKindOfClass, isMemberOfClass, isSubclassOfClass[/expand]
[expand tag=”div” title=”root classes?”]NSObject, NSProxy, id [/expand]
[expand tag=”div” title=”id type”]can be any object, but no native/primitive type[/expand]
[expand tag=”div” title=”how to make an object from a native/primitive type (boxing)?”]NSNumber, NSValue[/expand]
[expand tag=”div” title=”How methods are called? When the exact pointer is turns out”]message sending, runtime[/expand]
[expand tag=”div” title=”What is Notifications, NSNotificationCenter, local notification, push notification in general?”][/expand]
[expand tag=”div” title=”What’s necessary for the localization”] Localization strings files, NSLocalizedString[/expand]
[expand tag=”div” title=”How can you support a language which is not supported by the OS?”]put to strings file and load from the specified table (NSBundle localizedStringForKey:value:table:)[/expand]
[expand tag=”div”title=”Accessibility basics?”] AccessibilityLabel, accessibilityValue etc[/expand]
[expand tag=”div”title=”What is very important with long operations for example downloading something”] Background thread not to block UI. Use queues instead of threads[/expand]

Memory management

[expand tag=”div” title=”basic memory management topics: ownership”]retain/release/autorelease, ARC vs MRC[/expand]
[expand tag=”div” title=”what is retainCount, when to use”]reference count to the object. never use (helps for debug)- cannot access in ARC[/expand]
[expand tag=”div” title=”autorelease pool usage”][/expand]
[expand tag=”div” title=”what is a memory warning, how do we respond to it”][/expand]
[expand tag=”div” title=”ARC vs MRC”][/expand]
[expand tag=”div” title=”Can you use a library in ARC which were written using MRC?”]yes[/expand]
[expand tag=”div” title=”ARC bridging?”][/expand]
[expand tag=”div” title=”Reflection? Introspection? is there anything in objc and cocoa?”]YES. Advanced: objc_* class_*, object_* methods[/expand]

Threading

[expand tag=”div” title=”Threading possibilities – starting background tasks: nsthread vs nsoperationqueue vs GCD queues vs performselectorafterdelay”][/expand]
[expand tag=”div” title=”What is a deadlock, how can it happen?”][/expand]
[expand tag=”div” title=”How to make a code snippet thread safe?”]@synchronized[/expand]
[expand tag=”div” title=”How can you synchronize threads (and with timeout)?”] @synchronized, NSCondition[/expand]
[expand tag=”div” title=”When and why to create thread (with one of the thread technics)?”][/expand]
[expand tag=”div” title=”When to start a real NSThread?”]Very rare – use alternate instead[/expand]
[expand tag=”div” title=”What is the first thing to do on a thread and why?”]Create autorelease pool[/expand]
[expand tag=”div” title=”What is GCD? Benefits, general behavior?”]OS handles threads – very optimal[/expand]
[expand tag=”div” title=”When to use dispatch queues”]As often as possible when a thread necessary[/expand]
[expand tag=”div” title=”Main dispatch queue types: main, background, serial – when to use which and why”][/expand]
[expand tag=”div” title=”Benefit of NSOperationQueues”] priorities, cancellations: but you have to implement cancellation, you can implement the same with the other solutions as well…[/expand]
[expand tag=”div” title=”What is a runloop, where it is very commonly used”]Timers, NSUrlConnection[/expand]
[expand tag=”div” title=”What happens when you create a block?”]created on the stack, copy moves to the heap. copies the context’s variables[/expand]
[expand tag=”div” title=”Can you modify a variable out of the scope of a block?”]YES, __block variables[/expand]
[expand tag=”div” title=”difference between dispatch_sync and dispatch_async”][/expand]

Networking

[expand tag=”div” title=”When to use NSUrlRequest download methods and when to use delegate implementation?”][/expand]
[expand tag=”div” title=”What you should listen when download something from the internet”]NSURLConnection, NSRequest. Download in background. You should present in the UI: activity indicator in status bar or in separate view[/expand]
[expand tag=”div” title=”What is the difference between synchronous and asynchronous requests”][/expand]

UIKit

[expand tag=”div” title=”Base classes and general description”]UIResponder, UIView, UIControl[/expand]
[expand tag=”div” title=”How the event handling happens?”][/expand]
[expand tag=”div” title=”Difference between UIWindow and UIView”][/expand]
[expand tag=”div” title=”Can we have more UIWindows in iOS?”]Yes, but rare – UIAlertView is a separate window[/expand]
[expand tag=”div” title=”Difference between bounds, frame of a view”][/expand]
[expand tag=”div” title=”What’s very important designing UIs (views)?”]different resolutions, horizontal-vertical orientation, iOS7 sucks[/expand]
[expand tag=”div” title=”Difference between points and pixels”][/expand]
[expand tag=”div” title=”What is the responder chain?”]becomeFirstResponder ??? routing of touch messages – hittest, views passes to viewcontrollers then window ???[/expand]
[expand tag=”div” title=”What is IBOutlet and IBAction? How do you use them?”][/expand]
[expand tag=”div” title=”Basic tableview how to: datasource and delegate implementation”][/expand]
[expand tag=”div” title=”Drawbacks of UITableViews”]only vertical… ???[/expand]
[expand tag=”div” title=”Collection views”][/expand]
[expand tag=”div” title=”Benefits of collections views”][/expand]
[expand tag=”div” title=”What is very important updating the UI in a multithreaded application? How can you do that?”]update only on main thread/ main queue[/expand]
[expand tag=”div” title=”what to do when the keyboard appears and hides some parts of the UI that are important – logic implementation”]scrollview and keyboard notification handling[/expand]
[expand tag=”div” title=”Why should we release the outlets in viewDidUnload in MRC? What about ARC?”][/expand]
[expand tag=”div” title=”Difference in Xib/storyboard vs nib?”]xib and storyboard are xml but nib is binary – resource compiling”][/expand]
[expand tag=”div” title=”Animations?”][/expand]
[expand tag=”div” title=”view transitions?”]push, modal, custom, (embed? in segue)[/expand]
[expand tag=”div” title=”how can we present new view controllers?”]modal vs push[/expand]
[expand tag=”div” title=”tabbar vs toolbar vs navigationbar: when to use which, can you combine them?”][/expand]
[expand tag=”div”  title=”UI customization (possible ways to set color etc)”]use public properties, use appearance[/expand]
[expand tag=”div” title=”UIAppearance basics, difference between setting through appearance proxy and instance”]

  • appearance proxy: modifying a property on the proxy object=all instances gets the value;
  • modifying a property on an instance: just the instance gets modified; now can change more than previously. UI_APPEARANCE_SELECTOR marks these properties.

For example, to modify the bar tint color for all UINavigationBar instances: [[UINavigationBar appearance] setBarTintColor:myColor] VS &#91(UINavigationBar *)aUINavigationBar setBarTintColor:myColor]
[/expand]

CoreData

[expand tag=”div” title=”what is CoreData and what do we use it for”][/expand]
[expand tag=”div” title=”is CoreData == sqlite or some wrapper?”]on iOS it supports binary database, SQLite, in memory – on MAC it supports xml as well[/expand]
[expand tag=”div” title=”what types of stores does core data support”][/expand]
[expand tag=”div” title=”What is the minimum necessary classes and relationship between them?”]NSPersistentStore, NSPersitentStoreCoordinator, NSManagedObjectModel, NSManagedObjectContext[/expand]
[expand tag=”div” title=”Can the NSPersistentStoreCoordinator have more persistent stores?”]YES – but cannot handle if the same class is in different stores – can handle if separate or related classes are in different stores[/expand]
[expand tag=”div” title=”What is a managed object context”][/expand]
[expand tag=”div” title=”What about multi-threading and core data usage”]contexts aren’t thread safe ??? after iOS5?[/expand]
[expand tag=”div” title=”What is an NSManagedObjectId”]unique id, shareable; we can save it for later if the application was stopped[/expand]
[expand tag=”div” title=”What is lazy loading, how does this relate to core data, situations when this can be handy”][/expand]
[expand tag=”div” title=”How to read only a few attributes of an entity”][/expand]
[expand tag=”div” title=”What is a fetchedresultcontroller”][/expand]
[expand tag=”div” title=”How to synchronize contexts”][/expand]
[expand tag=”div” title=”How could one simulate an NSManagedObject (dynamic properties)”][/expand]

Tricky questions

[expand tag=”div” title=”What is an actual class in ObjectiveC”] struct … [/expand]
[expand tag=”div” title=”What is the isa member”]…[/expand]
[expand tag=”div” title=”How to make a static library optional?”]runtime class and method checks – NSClassFromString, respondsToSelector etc[/expand]
[expand tag=”div” title=”How to correctly implement a retaining setter property”]retain the parameter before release the old saved value[/expand]
[expand tag=”div” title=”How to declare the properties to work the same in MRC and ARC?”] strong=retain, unsafe_unreatained=assign etc ???[/expand]
[expand tag=”div” title=”What happens if you add your just created object to a mutable array, and you release your object”][/expand]
[expand tag=”div” title=”What happens with the objects if the array is released”][/expand]
[expand tag=”div” title=”What happens if you remove the object from the array/dict, and you try to use it”]Crash. you should get it first, retain, than remove from the array/dict[/expand]
[expand tag=”div” title=”Garbage collection on iPhone”] – none, similar: ARC, (autoreleasepool)[/expand]
[expand tag=”div” title=”The circular reference problem with delegates”]delegates being usually saved with assign rather then retain. Exception: NSURLConnection[/expand]
[expand tag=”div” title=”What happens when we invoke a method on a nil pointer?”]Nothing. Well known solution in ObjC[/expand]
[expand tag=”div” title=”What happens when we call a method on an object which doesn’t exists?”]Crash[/expand]
[expand tag=”div” title=”Does KVO works with iVars?”] NO. Why? observation messages is sent by the properties[/expand]
[expand tag=”div” title=”Does KVC works with iVars?”] YES. why?[/expand]
[expand tag=”div” title=”When it is mandatory to synthesize properties”]if declared in protocols[/expand]
[expand tag=”div” title=”What to do in a situation when a class not necessarily implement a method from a protocol”]This could happen when the method is optional, check with respondsToSelector[/expand]
[expand tag=”div” title=”Difference between nil and Nil and NULL???”][/expand]
[expand tag=”div” title=”How does proxy-ing work ???”][/expand]
[expand tag=”div” title=”How to call a method on an ‘unknown’ typed object?”]performSelector vs objc_msgSend vs etc…???[/expand]
[expand tag=”div” title=”How to call a selector with more than 2 parameters?”] NSInvocation, or declare block instead if possible, or objc_msgSend, or simply use object as ‘id’ and call the selector as simple method (creates warnings)[/expand]
[expand tag=”div” title=”How to cancel a block?”][/expand]
[expand tag=”div” title=”How NSOperation cancellation works?”]you have to implement in your code by listening the cancelled flag[/expand]
[expand tag=”div” title=”Can we/should we invoke (public) instance methods in an initializer and the dealloc? what about properties?”]subclass can override (don’t know what will happen, properties fires KVC notifications=don’t know what happens when one listens)[/expand]
[expand tag=”div” title=”NSCoding, NSKeyedArchiving”][/expand]
[expand tag=”div” title=”Can we use our own objects as key in a dictionary?”] No. What to do to solve the problem – implement NSCopying[/expand]
[expand tag=”div” title=”The difference between a shallow and a deep copy”][/expand]
[expand tag=”div” title=”What can’t we put into an array or dictionary?”]nil, objects not implementing NSCopying[/expand]
[expand tag=”div” title=”How can we put nil it into dictionary/array?”] NSNull [/expand]
[expand tag=”div” title=”How to get the current language of the device?”][NSLocale currentLocale] wrong it gives the Region!!!: use [NSLocale preferredLanguages][0];[/expand]