Friday, October 10, 2014

Core Data Multithreading / Concurrency with Core Data

Basic rules are:
  1. Use one NSPersistentStoreCoordinator per program. You don't need them per thread.
  2. Create one NSManagedObjectContext per thread.
  3. Never pass an NSManagedObject on a thread to the other thread.
  4. Instead, get the object IDs via -objectID and pass it to the other thread.
More rules:
  1. Make sure you save the object into the store before getting the object ID. Until saved, they're temporary, and you can't access them from another thread.
  2. And beware of the merge policies if you make changes to the managed objects from more than one thread.
  3. NSManagedObjectContext's -mergeChangesFromContextDidSaveNotification: is helpful.


Wednesday, July 16, 2014

Swift - String in swift [ swift programming language apple ios]

Strings 
“Swift strings are represented by the String type, which in turn represents a collection of values of Character type.”
“Unicode-compliant way to work with text in your code. ”
“Swift’s String type is bridged seamlessly to Foundation’s NSString class. ”

“Each Character value represents a single Unicode character.”

“+” to concate string

like format string let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5).


Swift - Some basic about swift / let var in swift [ swift programming language apple ios]

basic
no smicolon(“Semicolons are required, however, if you want to write multiple separate statements on a single line:”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/in/jEUH0.l), no backet for if , for loop, while loop
let - constant
var for variable
defualt compulsory for switch, no break
All swift code is unicode.
Even u can name variable as unicode character (use option + any key)
type-safe programming language for Cocoa development.
Swift has been in development for 4 years, and was just announced this year at WWDC.
automatic type identification.  The compiler infers it from what value is being set to the variable.

let π = 3.14159
let 你好 = "你好世界"

let 🐶🐮 = "dogcow”

Swift - Basic data types in swift [ swift programming language apple ios]

Integer
UInt8, Int32,Int64,UInt32,UInt64 etc

Float
Double,Float

“Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits.”

BOOL
Bool
Boolean constant values, true and false:”
Swift’s type safety prevents non-Boolean values from being be substituted for Bool. The following example reports a compile-time error:

let i = 1
if i {
    // this example will not compile, and will report an error

}”

Characters
“Each Character value represents a single Unicode character.”

Swift - Generics (like template in c++) [ swift programming language apple ios]

Generics (like template in c++)
“func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
    var result = ItemType[]()
    for i in 0..times {
        result += item
    }
    return result
}
repeat("knock", 4)”

“// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
    case None
    case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)”


Swift - category in Swift / Extension in swift [ swift programming language apple ios]

Extension like category
“Use extension to add functionality to an existing type, such as new methods and computed properties. ”
“extension Int: ExampleProtocol {
    var simpleDescription: String {
    return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
7.simpleDescription”


Swift - Protocol in swift [ swift programming language apple ios]

Protocol
“Classes, enumerations, and structs can all adopt protocols.”
protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}

“ mutating keyword in the declaration of SimpleStructure to mark a method that modifies the structure.”

Swift - enum / Enumeration [ swift programming language apple ios]

enum
enum like classes and have methods inside it.
enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescription() -> String {
        switch self {
        case .Ace:
            return "ace"
        case .Jack:
            return "jack"
        case .Queen:
            return "queen"
        case .King:
            return "king"
        default:
            return String(self.toRaw())
        }
    }
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()



Swift - Classes / Classes in Swift [ swift programming language apple ios]

Classes:-
use class keyword followed by classname

class Shape  {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}”

“init” and “deinit” like constructor and destructor resp.

class Square: NamedShape    // subclasing
{
var perimeter: Double {//getter and setter
    get {
        return 3.0 * sideLength
    }
    set {
        sideLength = newValue / 3.0
    }
    }

}


“If you don’t need to compute the property but still need to provide code that is run before and after setting a new value, use willSet and didSet. ”
class TriangleAndSquare {
    var triangle: EquilateralTriangle {
    willSet {
        square.sideLength = newValue.sideLength
    }
    }
    var square: Square {
    willSet {
        triangle.sideLength = newValue.sideLength
    }
    }
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
triangleAndSquare.triangle.sideLength


Swift - Function declaration and defination [ swift programming language apple ios]

Function declaration and defination
“Use func to declare a function.”
“func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}”

“Functions can be nested.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/in/jEUH0.l
return multiple values
“func getGasPrices() -> (Double, Double, Double) {
    return (3.59, 3.69, 3.79)
}”

like block
“numbers.map({
    (number: Int) -> Int in
    let result = 3 * number
    return result

    })”

Monday, May 5, 2014

What is ipa in iPhone / Creating ipa file in iPhone

What is ipa ?

A .ipa file is an iOS application archive file which stores an iOS app. It is usually encrypted with Apple's FairPlay DRM technology. Each .ipa file is compressed with a binary for the ARM architecture and can only be installed on an iOS-device.

.IPA files cannot be installed on the iPhone Simulator because they do not contain a binary for the x86 architecture. 

How to create ipa?
There are multiple ways you can create the ipa file .

1.With the help of iTunes

  1. Select device as target  in Xcode and make build.
  2. Go to Products in xcode  , select yourAppName.app. Right click and show in finder.
  3. Launch itunes
  4. Drag & drop  provisioning  profile and .app file to itunes's app section.
  5. Select app in iTunes and right click to show in Finder. And there you can get the .ipa file.
2.With the Xcode
  1. 1. Select device as target  in Xcode and make build.
  2. XCode choose Build > Build & Archive in old xcode  (in xcode 5 goto product -> Archive)
  3. in Xcode window-> organiser . You will get your archived apps
  4. Select one, hit 'Share...' and 'Save to Disk'

Tuesday, April 8, 2014

Dismiss keypad or keyboard in iphone

use

    [self.view endEditing:YES];

it will dismiss keypad

Moving from portrait view to Landscape view / Potrait UI orientation to landscape Ui orienttion in Phone iOS / Ui Orientation according to device Orientation / manually forcing orientation / change orientation manually


When u are switching from one view to another view .
First view is Portrait mode and next mode is in Landscape mode . 
Even u have implemented
-(BOOL)shouldAutorotate;
-(NSUInteger)supportedInterfaceOrientations;
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration;



USe 
+ (void)attemptRotationToDeviceOrientation

Attempts to rotate all windows to the orientation of the device.


-(void) viewDidAppear:(BOOL)animated
{
    [UIViewController attemptRotationToDeviceOrientation];
    [super viewDidAppear:animated];
}

-iPhone backboardd[52] : failed to resume in time

Some times u are getting this error
Feb 27 13:18:45 -iPhone backboardd[52] <Warning>: com.xyz.abc failed to resume in time

Main cause for this is the load on main thread. 
Try to avoid calling blocking calls for long time on main thread.
Create separate threads for such things.

If u know steps to reproduce follow steps find load on main thread also 
find performSelectorOnMainThread function used and get called at the same time.

try to avoid call many performSelectorOnMainThread functions.
Which crates extra burden on main thread.



iOS Architecture [ iPhone ]

reference:-http://www.techotopia.com/
iOS  Architecture




Application runs above the Cocoa Touch layer. Application can call any of layer to perform task.
Abstraction increments as layer goes away from hardware.

1. COCOA touch layer:-

Its upper layer written in objective C and derived (modified and extended ) standard Mac OS X Cocoa API. It consists of following frameworks.
 UIKit.framework - IT's UIkit framework. It contains application lifecycle management, event handling, UI creation and management, multitasking, cut copy paste functionality,Data protection,  Push Notification Service, Local notifications (a mechanism whereby an application running in the background can gain the user’s attention), gesture recognition., file sharing, Accelerometer, battery, proximity sensor, camera and photo library interaction. 
iAd.framework - to display advertising in the application. All advertisements are served by Apple’s own ad service.
MessageUI.framework- used in application to compose and send mail.
MapKit.framework:- used in app to use map related services.
AddressUI.framework:-used for to access, display, edit and enter contact information.
GameKit.framework:-provides framework for multiplayer game.
Push Notification Service :- for allow application to notify the user when application is not running.
Event Kit UI Framework:-to access and edit calendar event.

2. Media Services Layer


This layer provides audio, video , animation and graphics services to application developer.

CoreVideo.framework:- for video purpose, even with  streaming video support (network)
CoreText.framework:-for text layout and font
ImageIO.framework:- for importing and exxporting of image data and image metadata
AssetsLibrary.framework:- For finding and accesing photo and video files. adding new photo and videos to album.
CoreGraphics.framework( Quartz 2D API):-provide 2D rendering engine, support creation and presentation of pdf , vector based drawing , transparent layer,image rendering and gradient
QuartzCore.framework:-For animation and visual effects.
OpenGLES.framework:-for high performance 2D and 3D drawing
iOS Audio Support:- audio in AAC, Apple Lossless (ALAC), A-law, IMA/ADPCM, Linear PCM, µ-law, DVI/Intel IMA ADPCM, Microsoft GSM 6.10 and AES3-2003 formats
AVFoundation.framework:-playback, recording and management of audio content. this is objective C based
Core Audio Frameworks (CoreAudio.framework, AudioToolbox.framework and AudioUnit.framework):-playback and recording of audio files and streams and also provide access to the device’s built-in audio processing units.
OpenAL:- provide high-quality, 3D audio effects, typically using to provide sound effects in games.
MediaPlayer.framework:-is able to play video in .mov, .mp4, .m4v, and .3gp formats
CoreMIDI.framework:-to interact with MIDI compliant devices such as synthesizers and keyboards 

3.iOS Core Services Layer

this layer provides the foundation on which the above layer built.
AddressBook.framework:- access to addressbok contact database . add , modify, delete contactCFNetwork.framework:-provides a C-based interface to the TCP/IP networking protocol stack and low level access to BSD sockets. This enables application code to be written that works with HTTP, FTP and Domain Name servers and to establish secure and encrypted connections using Secure Sockets Layer (SSL) or Transport Layer Security (TLS).
CoreData.framework:-to ease the creation of data modeling and storage in Model-View-Controller
CoreFoundation.framework:- C-based Framework. provides basic functionality such as data types, string manipulation, raw block data management, URL manipulation, threads and run loops, date and times, basic XML manipulation and port and socket communication.
CoreMedia.framework:- lower level foundation upon which the AV Foundation layer is built
CoreTelephony.framework:- to access data related to telephony part.

EventKit.framework:-access to the calendar and alarms on the device.
Foundation.framework:-consists of Objective-C wrappers around much of the C-based Core Foundation Framework.
CoreLocation.framework:-to obtain the current geographical location of the device  and compass readings This will either be based on GPS readings, Wi-Fi network data or cell tower triangulation (or some combination of the three).
MobileCoreServices.framework:-identifying data types as text, RTF, HTML, JavaScript, PowerPoint .ppt files, PhotoShop images and MP3 files.
StoreKit.framework:- to facilitate commerce transactions between your application and the Apple App Store.  user can be given the option make additional payments from within the application.
SQLite library:-or a lightweight, SQL based database to be created and manipulated from within your iPhone application.
SystemConfiguration.framework:-allows applications to access the network configuration settings of the device to establish information about the “reachability” of the device (for example whether Wi-Fi or cell connectivity is active and whether and how traffic can be routed to a server).
QuickLook.framework:-provides a useful mechanism for displaying previews of the contents of files types loaded onto the device (typically via an internet or network connection) for which the application does not already provide support. File format types supported by this framework include iWork, Microsoft Office document, Rich Text Format, Adobe PDF, Image files, public.text files and comma separated (CSV).


4.iOS Core OS layer

sits directly on top of the device hardware.provides a variety of services including low level networking, access to external accessories and the usual fundamental operating system services such as memory management, file system handling and threads.

Accelerate.framework:-C-based API for performing complex and large number math, vector, digital signal processing (DSP) and image processing tasks and calculations.
ExternalAccessory.framework:-to interrogate and communicate with external accessories connected physically to the iPhone via the 30-pin dock connector or wirelessly via Bluetooth
Security.framework:-provides all type  of security interfaces including connect to external networks including certificates, public and private keys, trust policies, keychains, encryption, digests and Hash-based Message Authentication Code (HMAC)
LibSystem(System):-iOS is built upon a UNIX-like foundation. component of the Core OS Layer provides much the same functionality as any other UNIX like operating system.This layer includes the operating system kernel  and device drivers. provides the low level interface to the underlying hardware. kernel is responsible for memory allocation, process lifecycle management, input/output, inter-process communication, thread management, low level networking, file system access and thread management.As an app developer your access to the System interfaces is restricted for security and stability reasons. 






different type of Application template [ iPhone ] [ xcode ]

Different types of templates in XCode

There are different types of application template in XCode.
Navigation-based Application :- creation application which will having navigation from one view to other.
Open GL ES Application:-creates a basic application containing an Open GL ES view upon which to draw and manipulate graphics.
Split View Application :- An iPad only application template with a user interface containing two views in a master-detail configuration whereby a one view provides a list and second displays detailed information corresponding to the current list selection.
Tab Bar Application:-Creates a template application with a tab bar. tab bar typically appears across the bottom.
Utility Application:- Creates a template consisting of a two sided view.
View-based Application – Creates a basic template for an application containing a single view.
Window-based Application – The most basic of templates and creates only a window and a delegate.


The company identifier is typically the reversed URL of your company’s website, for example “com.mycompany”. This will be used when creating provisioning profiles and certificates to enable applications to be tested on a physical iPhone device.

Objective C source files have .m extension and  header or interface files .h extension.
.xib files have User interface created .
 .plist file extension are Property List files that contain key/value pair information , contains such as the language, icon file, executable name and app identifier..

Summary screen, tabs are provided to view and modify additional settings consisting of Info, Build Settings, Build Phases and Build Rules.

Frequently used Design pattern used in iPhone Programming [ iPhone ] [ iOS ]

Model View Controller 

Model encapsulates the data for the application, the View presents and manages the user interface and the Controller provides the basic logic for the application and acts as the go-between, providing instructions to the Model based on user interactions with the View and updating the View to reflect responses from the Model. 
the Model knows absolutely nothing about the presentation of the application. View knows nothing about the data and logic model of the application.
App can consist of multiple view objects, controller objects and model objects.
view controller object interacts with a Model is through the methods and properties exposed by that model object.

Target-Action pattern

In the Target-action design pattern the object contains the necessary information to send a message to another object when an event occurs.  where a computer program is divided up into objects which dynamically establish relationships by telling each other which object they should target and what action or message to send to that target when an event occurs. This is especially useful when implementing graphical user interfaces, which are by nature event-driven.
Action methods are declared using the IBAction keyword. and targets are declared using 
IBOutlets.  Here IB is for interface builder.

Subclassing


Subclassing allows us to create a new class by deriving from an existing class and then extending the functionality. we get all the functionality of the parent class combined with the ability to extend the new class with additional methods and properties.

Delegation



Delegation allows an object to pass the responsibility for performing one or more tasks on to another object. This allows the behavior of an object to be modified without having to go through the process of subclassing it.

Handling AddressBook in iphone [ iOS ]


ABAddressBookRef is class in iOS used to access the address book (a centralized database used by multiple application). with this class we can add, modify, delete the contact.

Create new address book object  from address book database.:-

ABAddressBookRef pAddressBook = ABAddressBookCreateWithOptions(NULL, &error);

Each record in the Address Book database hase a unique ID , which you can retrive by ABRecordGetRecordID function.

 ABRecordRef class holds one record inside.
You can access records as follows

ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
CFArrayRef allSources = ABAddressBookCopyArrayOfAllSources(addressBook);

for (CFIndex i = 0; i < CFArrayGetCount(allSources); i++) 

        {
ABRecordRef source = (ABRecordRef)CFArrayGetValueAtIndex(allSources, i);
      }

Display loading indicator / Activity Indicator / daisy wheel in top status bar [ iPhone ]


In UIApplication:
To start indicator:-
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
To stop indicator

UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;



About ViewController / view Controller in iPhone [ iOS ]

View Controllers are the link between data and view(visual appearance). Whenever iOS displays anything on screen it is managed by the ViewController or group of ViewControllers coordinating with each other ViewController provides the skeletal framework on which we can build our application.

iOS provides many built-in view controller classes to support standard user interface pieces, such as navigation and tab bars. You can write ur own custom view-controller.

Below image and article reference (apple website source:-http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html)



ViewController manages set of views. It provides view that can be displayed or interacted with it. Normally viewcontrollers have one root view which consists of multiple view like button, editbox etc.

Container View Controllers Manage Other View Controllers. One viewcontroller may consists of multiple view controller by forming parent-child relationship with single root viewcontroller..

We can switch to another viewcontroller from current one. Navigation controller is used for switching one view to another. Navigation controller keeps all viewcontroller in stack ways. So if displayed view is poped u will go to previous view.

A key part of any view controller’s implementation is to manage the views used to display its content. 

View-Controller manages views also they are coordinate with each other.

How View Controllers Present Other View Controllers

The view controller that did the presenting updates its presentedViewControllerproperty to point to its presented view controller. Similarly, the presented view controller updates its presentingViewControllerproperty to point back to the view controller that presented it.

 you can chain presented view controllers together, presenting new view controllers on top of other view controllers as needed.
Each view controller in a chain of presented view controllers has pointers to the other objects surrounding it in the chain. In other words, a presented view controller that presents another view controller has valid objects in both its presentingViewController andpresentedViewController properties. You can use these relationships to trace through the chain of view controllers as needed. Ex:you can remove all objects in the chain by dismissing the first presented view controller. 

When presenting a navigation controller, you always present the UINavigationController object itself, rather than presenting any of the view controllers on its navigation stack. However, individual view controllers on the navigation stack may present other view controllers, including other navigation controllers. 

Figure 10-3  Presenting navigation controllers modally

As you can see, the people picker is not presented by the photo library navigation controller but by one of the content view controllers on its navigation stack.

Listing 10-1  Presenting a view controller programmatically
/ Create the root view controller for the navigation controller
   // The new view controller configures a Cancel and Done button for the
   // navigation bar.
   RecipeAddViewController *addController = [[RecipeAddViewController alloc]
                       init];
 
   // Configure the RecipeAddViewController. In this case, it reports any
   // changes to a custom delegate object.
   addController.delegate = self;
 
   // Create the navigation controller and present it.
   UINavigationController *navigationController = [[UINavigationController alloc]
                             initWithRootViewController:addController];
   [self presentViewController:navigationController animated:YES completion: nil];






Lazy Instantiation in Objective-C [ iphone ] [ iOS ] [ Objective C ]

Lazy Instantiation (initialisation ) , this technique is good if you have an object that only needs to be configured once and has some configuration involved that you don't want to clutter your init method.

Means in init method does not initialising the object. Initialise  object somewhere else in other method of the same class  may be accessor etc.


So you want an NSMutableArray property. You could alloc init it in some method before you use it, but then you have to worry about "does that method get called before I need my array?" or "am I going to call it again accidentally and re-initalize it."
So a failsafe place to do it is in the property's getter. It gets called every time you access the property.

Example

.h

@property (nonatomic, strong) NSMutableArray* myArray;.m@synthesize myArray = _myArray;- (NSMutableArray*) myArray{
if (!_myArray){ _myArray = [[NSMutableArray alloc] initWithCapacity:2];}
return _myArray;}
Every time you access that property, it says, "Does myArray exist? If not, create it. If it does, just return what I have."




Thursday, January 30, 2014

App ID in iOS / App ID in iPhone

An App ID is a two-part string used to identify one or more apps from a single development team. The string consists of a Team ID and abundle ID search string, with a period (.) separating the two parts.The Team ID is supplied by Apple and is unique to a specific development team, while the bundle ID search string is supplied by you to match either the bundle ID of a single app or a set of bundle IDs for a group of your apps.


An Explicit App ID Matches a Single App
Wildcard App IDs Match Multiple Apps
There are two types of App IDs: an explicit App ID, used for a single app, and wildcard App IDs, used for a set of apps.
For an explicit App ID to match an app, the Team ID in the App ID must equal the Team ID associated with the app, and the bundle ID search string must equal the bundle ID for the app. The bundle ID is a unique identifier that identifies a single app and cannot be used by other teams.
A wildcard App ID contains an asterisk as the last part of its bundle ID search string. The asterisk replaces some or all of the bundle ID in the search string.


The asterisk is treated as a wildcard when matching the bundle ID search string with bundle IDs. For a wildcard App ID to match a set of apps, the bundle ID must exactly match all of the characters preceding the asterisk in the bundle ID search string. The asterisk matches all remaining characters in the bundle ID. The asterisk must match at least one character in the bundle ID. The table below shows a bundle ID search string and some matching and nonmatching bundle IDs.

Object copying in iOS / Object copying in iPhone / copy function call in iOS iPhone / what will happen when we call copy on object

Object copying
Copying an object creates a new object with the same class and properties as the original object. You copy an object when you want your own version of the data that the object contains. If you receive an object from elsewhere in an application but do not copy it, you share the object with its owner (and perhaps others), who might change the encapsulated contents. 

Requirements for Object Copying

An object can be copied if its class adopts the NSCopying protocol and implements its single method, copyWithZone:
If a class has mutable and immutable variants, the mutable class should adopt the NSMutableCopying protocol (instead of NSCopying) and implement the mutableCopyWithZone: method to ensure that copied objects remain mutable. You make a duplicate of an object by sending it a copyor mutableCopy message. These messages result in the invocation of the appropriate NSCopying or NSMutableCopying method.

Copies of objects can be shallow or deep. Both shallow- and deep-copy approaches directly duplicate scalar properties but differ on how they handle pointer references, particularly references to objects (for example, NSString *str). A deep copy duplicates the objects referenced while a shallow copy duplicates only the references to those objects. So if object A is shallow-copied to object B, object B refers to the same instance variable (or property) that object A refers to. Deep-copying objects is preferred to shallow-copying, especially with value objects.


Memory-Management Implications
Like object creation, object copying returns an object with a retain count of 1. In memory-managed code, the client copying the object is responsible for releasing the copied object. Copying an object is similar in purpose to retaining an object in that both express an ownership in the object. However, a copied object belongs exclusively to the new owner, who can mutate it freely, while a retained object is shared between the owners of the original object and clients who have retained the object.


what is Selector in iOS / what is Selector in iPhone

 A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled.  A selector by itself doesn’t do anything. It simply identifies a method. compiler makes sure that selectors are unique.

What makes a selector useful is that (in conjunction with the runtime) it acts like a dynamic function pointer that, for a given name, automatically points to the implementation of a method appropriate for whichever class it’s used with.

Getting a Selector
At compile time, you use the compiler directive @selector.
SEL aSelector = @selector(methodName);

SEL aSelector = NSSelectorFromString(@"methodName");

Using a Selector
SEL aSelector = @selector(run);
[aDog performSelector:aSelector];
[anAthlete performSelector:aSelector];
[aComputerSimulation performSelector:aSelector];


At runtime, you use the NSSelectorFromString function, where the string is the name of the method:
You use a selector created from a string when you want your code to send a message whose name you may not know until runtime.

Compiled selectors are of type SEL. There are two common ways to get a selector:
You can invoke a method using a selector with performSelector: and other similar methods.
(You use this technique in special situations, such as when you implement an object that uses the target-action design pattern. Normally, you simply invoke the method directly.)

Monday, January 6, 2014

what is dispatch_once() in iOS / dispatch_once() in iOS

Executes a block object once and only once for the lifetime of an application.
This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.
If called simultaneously from multiple threads, this function waits synchronously until the block has completed.
The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.
dispatch_once() is absolutely synchronous. Not all GCD methods do things asynchronously (case in point, dispatch_sync() is synchronous). The use of dispatch_once() replaces the following idiom:

+ (MyClass *)sharedInstance {
    static MyClass *sharedInstance;
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[MyClass alloc] init];
        }
    }
    return sharedInstance;
}

The benefit of dispatch_once() over this is that it's faster. It's also semantically cleaner, because the entire idea of dispatch_once() is "perform something once and only once", which is precisely what we're doing.


About

Blog Archive

Powered by Blogger.

Blog Archive