A good presentation about unit testing – the proper way đ
https://vimeo.com/108007508
A good presentation about unit testing – the proper way đ
https://vimeo.com/108007508
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 …
}
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
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:
class YourSwiftClass : NSObject
class func newInstance() -> YourSwiftClass { return YourSwiftClass() }
class func alloc() -> YourSwiftClass { return YourSwiftClass() }
[[NSClassFromString(@"YourProjectName.YourSwiftClass") alloc] init]
@interface YourSwiftClass (allocation) + (instancetype)alloc; @end
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â
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
The main reason of this document is to help to achieve a clean code, which is:
There are two types of comments regarding the target:
For comments keep in mind the following basic rules:
Can vary between projects but must be uniform in one project. Good practice to use the default formatting of the IDE/language.
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.
There are more solutions how to select items from a list randomly
Initial steps:
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.
[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.
[/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]
[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]
[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]
[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]
[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”]
For example, to modify the bar tint color for all UINavigationBar instances: [[UINavigationBar appearance] setBarTintColor:myColor] VS [(UINavigationBar *)aUINavigationBar setBarTintColor:myColor]
[/expand]
[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]
[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]