Skip to main content

iOS Beginner Level [Part 2/4]: Familiar Objective-C Classes


[1] NSUserDefaults
NSUserDefaults object used to read information and caches information in user’s default data base.  Stores the data in Plist. The synchronised method of this class automatically invoked at a period of intervals to sync  the memory cache the data base. ex: `[defaults synchronize];`
Always returns the immutable values. Non-persistent data storage.

[2] NSBundle 
This object locates your app in the file system from where you can access resources and use them in your programs.

[3] UIResponder: 
Subclass of NSObject defines the interface for objects ( likely abstract class) objects responds to this class and it handles those events. It is the super class of UIApplication, UIWindow , UIView (including all of its subclasses). Handles all type of touch events, motion events.

[4] NSCoder 
NSCoder is an abstractClass which represents a stream of data. They are used in Archiving and Unarchiving objects. NSCoder objects are usually used in a method that is being implemented so that the class conforms to the protocol. (which has something like encodeObject and decodeObject methods in them). 

[5] NSZombie
It’s a memory debugging aid. Specifically, when you set NSZombieEnabled then whenever an object reaches retain count 0, rather than begin deallocated it morphs itself into an NSZombie instance. Whenever such a zombie receives a message, it logs a warning rather than crashing or behaving in an unpredictable way. 


[6] NSOperationQueue
NSOperationQueue creates pool of threads and used to execute NSOperations parallel.
The class regulates the execution of a set of NSOperation objects. An operation queue is generally used to perform some asynchronous operations on a background thread so as not to block the main thread. 

[7] NSThread 
Creates low level thread which can be started by `start` method.

[8] NSTimer
NSTimer is a class which creates timer object and that timer object executes in certain time interval on other then main thread.

[9] Nil, nil, NULL, NSNil 
Nil - Specifies to class pointers.
nil - Specifies to objects (eg. id)
NULL - Refers to 0 (zero) to any pointers.
NSNil - Value ‘nil’ to store in Collections.

[10] @property
Properties are a feature in Objective-C that allow us to automatically generate accessors.
Properties has its own format, in this order: 
1. The definition of the property has to start with the @property keyword.
2. You then need to specify the qualifiers of the property. nonatomic properties are not thread-safe. You can also specify assign, copy, weak, strong, or unsafe_unretained as the property qualifiers.
3. You then have to specify the data type of the property, such as NSInteger or NSString.
4. Last but not least, you have to specify a name for the property.
Example @property(weak) NSString *firstName;

[11] Strong (<iOS4 = retain)
Create an owning relationship between the property and the assigned value. This is the default for object properties. Primitive data types are not allowed. Only objects or instance of classes are allowed.


[12] Weak (<iOS4 = unsafe_unretained )
Doest not takes the ownership of assigned value, instead it will keep the value as long as someone else points strongly. 

[13 ]Copy 
Same as ‘strong’ but at runtime will make a copy of the object. Hence the increment of ‘Reference count’ by 1. Create a copy of the assigned value instead of referencing the existing instance.  Instead of taking ownership of existing object, it creates a copy of whatever you assign to the property, then takes ownership of that.

[14] Assign 
Same as weak except, does not set to nil out after object released. Use assign for C primitive properties and weak for weak references to Objective-C objects.

[15] readonly
Declaring your property as readonly tells compiler not to generate setter method automatically.
If you specify readonly, only a getter method is required in the @implementation block. If you use the @synthesize directive in the @implementation block, only the getter method is synthesised.



[16] readwrite 
Default attribute where Setter and getter generated by the compiler. Both a getter and setter method are required in the @implementation block. If you use the @synthesize directive in the implementation block, the getter and setter methods are synthesised. To change or give custom name to accessor methods
Example: @property (getter = isFinished) BOOL finished;

 [17] Shallow copying vs Deep copy
A deep copy duplicates the objects referenced while a shallow copy duplicates only the references to those objects. Shallow is “by Reference”, Deep is “by Value”

[18] Copy vs mutableCopy
copy returns an immutable (can't be modified) copy of the object, 
mutableCopy returns a mutable (can be modified) copy of the object.

[19] Atomic
Atomic Thread safe. Slow performance when we access to ‘property’. Guaranties returning value is valid.

[20] Nonatomic
 Non thread safe. Faster access to property. Chance of race condition.

[21] @class 
 A forward declaration compiler directive, It tells the compiler that class exists, does not know anything about class.

[22] @synthesize
Directive automatically generates the setters and getters for us.

[23] @dynamic
 Just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass)
Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.

[24] @synchronized
The @synchronized()directive locks a section of code for use by a single thread. Other threads are blocked until the thread exits the protected code—that is, when execution continues past the last statement in the @synchronized() block.

[25] Backing variables
@property always have backing variable. For example,
@synthesise searchBar = _searchBar;
Here synthesise does is declare that backing variable for your searchbar will be called _searchbar.
This allows us decouple name of property from the name of the variable. If don’t use synthesise , you don’t need to have a backing variable at all. (Current Xcode internally adds synthesise directive)
To avoid clashes between variable name and make it clear when using a local variable and when using instance variable.

[26] new
Use “new” to create an object if no arguments are needed for initialisation.

[[XYZObject alloc] init] same as [XYZObject new]

Popular posts from this blog

Animating label text update - choosing a better way

Recently I published a countdown app .  At one point of development - I have to show a timer on a UILabel which ticks on each seconds. As usual I started  setting text to a label object - self .timerLabel.text = someString Easy piece of cake right !?   But wait ... it won't take much user attention when timer ticks on every seconds. So I decided to make use of a simple animation while label gets text update. I found there are dozens of ways to animate a label. In this short article, I listed 3 best way you can animate text on a label. ( Spoiler Alert 👀- I decided to go with 3rd option)  1. Fade In - Fade out animation : CATransition class has got transition type `fade`. With timing function of CATransition - I was able to see the below result. let animation: CATransition = CATransition () animation.timingFunction = CAMediaTimingFunction (name: CAMediaTimingFunctionName .easeInEaseOut) animation.type = CATransitionType .fade animation.subtype = CATransitionSubtype .

Prevent Navigationbar or Tabbar overlapping Subview - solved for Card view

Recently, I started with a Card view added as a subview of UIView in a view-controller. When a view controller created along subviews, it tends to use entire screen bounds and also slips behind Tab bar or Navigation bar. In my current situation, it's second case. Casually new iOS developers will write a patch by additional value for coordinate y and subtracting bar height from its size. A lot of them posted in SO threads too : How to prevent UINavigationBar from covering top of view? View got hidden below UINavigationBar iOS 7 Navigation Bar covers some part of view at Top So, how I got solved ? self.edgesForExtendedLayout = [] This  will avoid all subviews in a view controller get behind any bars. Read full apple  documentation on here. Full Source code below :  //Simple view controller where its view layed-out as a card. class WidgetCardViewController : UIViewController { var containerView = UIView () //MARK:- View Controller Life Cycle ov

UICollectionViewCell shows with wrong size on First time - Solved

We commonly use Collection view where its cell size calculated run time. The flow layout delegate is responsible to return individual cell sizes. BUT in most of the cases, delegate method `collectionView: layout sizeForItem:` expects cell size too early. Before generating actual cell size. extension YourViewController : UICollectionViewDelegateFlowLayout { func collectionView ( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize (width: externalWidth, height: externalHeight) } } For instance, if a cell size depends on external view and its frame is not yet ready - results with wrong (or outdated) cell size. Typically happens for the first time view controller laid out all views. You can find similar queries in StackOverflow community : Collection view sizeForItemNotWorking UICollectionViewCell content wrong size on first load How to refresh UICollection

Implementing autocompletion OTP field in iOS

Long waiting is over. !!  iOS 12 brings Autofill for OTP text field which is close to Android provided a decade back. Previously in iOS we used to toggle between OTP text screen and message inbox.  Which was hard to remember and time consuming resulting a bad user experience. Personally, I have been asked from the client/customer couple of times to implement autocompletion for OTP field and took me a lot of time to convey that it is not possible in iOS. Why Autofill was not possible previously?  We all know that Apple gives at most care for user privacy. When we see iOS architecture, each individual app is like a separate island. There is no inter-app bridge between apps (exception for Keychain and URLSchemes APIs which gives very limited scope). Thus we cannot read message content from inbox. Where to start Autofilling? First of all, the target SMS need to have the OTP Code with prefix string "Code" or "Passcode"on its message content. Beware of OTP c

Printing Staircase Pattern : Swift coding challenge

In this post, we can try interesting pattern printing challenge in Swift. The problem statement goes like this " Print a staircase of given size 'n'. Make sure that its base and height are both equal to n, and the image is drawn only using `#` symbols and spaces. The last line is not preceded by any spaces." Expected Output : # ## ### #### ##### ###### Working solution: func makePatternOf ( _ size : Int ) { var str = "" // 1 for index in ( 0 ..< size ) { let stop = size -index-1; // 2 for _ in 0 ..< stop { str. append ( " " ) ; } // 3 for _ in 0 .. . index { str. append ( "#" ) ; } print ( str ) str = "" } } makePatternOf ( 6 ) Loop to visit every row of stair case. Loop for appe