Category Archives: Apple

NSOperation – Tutorial

Operation Queues

GCD is a low-level C API that enables developers to execute tasks concurrently. Operation queues, on the other hand, are high level abstraction of the queue model, and is built on top of GCD. That means you can execute tasks concurrently just like GCD, but in an object-oriented fashion. In short, operation queues just make developers’ life even simpler.

Unlike GCD, they don’t conform to the First-In-First-Out order. Here are how operation queues are different from dispatch queues:

  1. Don’t follow FIFO: in operation queues, you can set an execution priority for operations and you can add dependencies between operations which means you can define that some operations will only be executed after the completion of other operations. This is why they don’t follow First-In-First-Out.
  2. By default, they operate concurrently: while you can’t change its type to serial queues, there is still a workaround to execute tasks in operation queues in sequence by using dependencies between operations.
  3. Operation queues are instances of class NSOperationQueue and its tasks are encapsulated in instances of NSOperation.

NSOperation

Tasks submitted to operation queues are in the form of NSOperation instances. We discussed in GCD that tasks are submitted in block. The same can be done here but should be bundled inside NSOperation instance. You can simply think of NSOperation as a single unit of work.

NSOperation is an abstract class which can’t be used directly so you have to use NSOperation subclasses. In the iOS SDK, we are provided with two concrete subclasses of NSOperation. These classes can be used directly, but you can also subclass NSOperation and create your own class to perform the operations. The two classes that we can use directly are:

  1. NSBlockOperation – Use this class to initiate operation with one or more blocks. The operation itself can contain more than one block and the operation will be considered as finish when all blocks are executed.
  2. NSInvocationOperation – Use this class to initiate an operation that consists of invoking a selector on a specified object.

So what’s the advantages of NSOperation?

    1. First, they support dependencies through the method addDependency(op: NSOperation) in the NSOperation class. When you need to start an operation that depends on the execution of the other, you will want to use NSOperation.
NSOperation Illustration
  1. Secondly, you can change the execution priority by setting the property queuePrioritywith one of these values:

    The operations with high priority will be executed first.

  2. You can cancel a particular operation or all operations for any given queue. The operation can be cancelled after being added to the queue. Cancellation is done by calling method cancel() in the NSOperation class. When you cancel any operation, we have three scenarios that one of them will happen:
    • Your operation is already finished. In that case, the cancel method has no effect.
    • Your operation is already being executing. In that case, system will NOT force your operation code to stop but instead, cancelled property will be set to true.
    • Your operation is still in the queue waiting to be executed. In that case, your operation will not be executed.
  3. NSOperation has 3 helpful boolean properties which are finished, cancelled, and ready. finished will be set to true once operation execution is done. cancelled is set to true once the operation has been cancelled. ready is set to true once the operation is about to be executed now.
  4. Any NSOperation has an option to set completion block to be called once the task being finished. The block will be called once the property finished is set to true in NSOperation.

Now let’s rewrite our project demo but this time we’ll use NSOperationQueues. First declare the variable below in the ViewController class:

Next, replace the didClickOnStart method with the code below and see how we perform operations in NSOperationQueue:

As you see in the above code, you use the method addOperationWithBlock to create a new operation with the given block (or as we call it in Swift, a closure). It’s very simple, isn’t it? To perform a task in the main queue, instead of calling dispatch_async() as when using GCD, we can do the same from NSOperationQueue (NSOperationQueue.mainQueue()) and submit the operation you want to execute in the main queue.

You can run the app to have a quick test. If the code was entered correctly, the app should be able to download the images in background without blocking the UI.

In the previous example, we used the method addOperationWithBlock to add operation in the queue. Let’s see how we can use NSBlockOperation to do the same, but at the same time, giving us more functionalities and options such as setting completion handler. The didClickOnStart method is rewritten like this:

For each operation, we create a new instance of NSBlockOperation to encapsulate the task into a block. By using NSBlockOperation, you’re allowed to set the completion handler. Now when the operation is done, the completion handler will be called. For simplicity, we just log a simple message to indicate the operation is done. If you run the demo, you would see something like this in console:

Canceling Operations

As mentioned before, NSBlockOperation allows you to manage the operations. Now let’s see how to cancel an operation. To do that, first add a bar button item to the navigation bar and name it Cancel. In order to demonstrate the cancel operation, we will add a dependency between Operation #2 and Operation #1, and another dependency between Operation #3 and Operation #2. This means Operation #2 will start after finishing of Operation #1, and Operation #3 will start after Operation #2 completes. Operation #4 has no dependency and will work concurrently. To cancel the operations all you need to do is call cancelAllOperations() of NSOperationQueue. Insert the following method in the ViewController class:

Remember you need to associate the Cancel button you added to the navigation bar with the didClickOnCancel method. You can do this by returning to the Main.storyboard file and opening the Connections Inspector. There you will see the unlink didSelectCancel() in the Received Actions section. Click + drag from the empty circle to the Cancel bar button. Then create the dependencies in the didClickOnStart method like this:

Next change the completion block of operation #1 to log the cancelled state like this:

You may change the log statement for operation #2, #3 and #4, so you will have a better idea of the process. Now let’s build and run. After you hit the Start button, press the Cancel button. This will cancel all operations after operation #1 completes. Here is what happens:

  • As operation #1 already executed, cancelling will do nothing. This is why the cancelled value is logged false, and the app still shows image #1.
  • If you hit the Cancel button quick enough, operation #2 is cancelled. The cancelAllOperations() call will stop its execution, so image #2 is not downloaded.
  • Operation #3 was already in the queue, waiting for operation #2 to complete. As it depends on the completion of operation #2 and operation #2 was cancelled, operation #3 will not be executed and kicked out immediately from the queue.
  • There is no dependency configured for operation #4. It just runs concurrently to download image #4.
ios-concurrency-cancel-demo

Where to go from here?

In this tutorial, I have walked you through the concept of iOS concurrency and how you can implement it in iOS. I have given you a good introduction about concurrency, explained GCD, and showed you how to create series and concurrent queues. Furthermore, we have checked out NSOperationQueues. You should now be comfortable with the difference between Grand Central Dispatch and NSOperationQueue.

To dive further into iOS concurrency, I advise you to check out Apple’s Concurrency Guide.

Original article in: http://www.appcoda.com/ios-concurrency/

UIAlertView in Swift

In Swift and iOS 8 SDK you can present an alert view as shown in the code below :

 

var alert = UIAlertController(title: “Alert Title”, message: “Message”, preferredStyle: UIAlertControllerStyle.Alert)alert.addAction(UIAlertAction(title: “OK”, style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

You can also add destructive and cancel actions by setting the style property to Destructive and Cancel respectively.

IBAction and Outlets

Actions

An action is a piece of code that’s linked to some kind of event that can occur in your app. When that event takes place, the code gets executed. You can define an action to accomplish anything from manipulating a piece of data to updating the user interface. You use actions to drive the flow of your app in response to user or system events.

You define an action by creating and implementing a method with an IBAction return type and a senderparameter.

  1. - (IBAction)restoreDefaults:(id)sender;

The sender parameter points to the object that was responsible for triggering the action. The IBAction return type is a special keyword; it’s like the void keyword, but it indicates that the method is an action that you can connect to from your storyboard in Interface Builder (which is why the keyword has the IB prefix).

Outlets

Outlets provide a way to reference objects from your interface—the objects you added to your storyboard—from source code files. You create an outlet by Control-dragging from a particular object in your storyboard to a view controller file. This creates a property for the object in your view controller file, which lets you access and manipulate that object from code at runtime. For example, in the second tutorial, you’ll create an outlet for the text field in your ToDoList app to be able to access the text field’s contents in code.

Outlets are defined as IBOutlet properties.

  1. @property (weak, nonatomic) IBOutlet UITextField *textField;

The IBOutlet keyword tells Xcode that you can connect to this property from Interface Builder.

Swift, Apple’s new programming language

If anyone outside Apple saw Swift coming, they certainly weren’t making any public predictions. In the middle of a keynote filled with the sorts of announcements you’d expect (even if the details were a surprise), Apple this week announced that it has created a modern replacement for the Objective-C, a programming language the company has used since shortly after Steve Jobs founded NeXT.

Swift wasn’t a “sometime before the year’s out”-style announcement, either. The same day, a 550-page language guide appeared in the iBooks store. Developers were also given access to Xcode 6 betas, which allow application development using the new language. Whatever changes were needed to get the entire Cocoa toolkit to play nice with Swift are apparently already done.

While we haven’t yet produced any Swift code, we have read the entire language guide and looked at the code samples Apple provided. What follows is our first take on the language itself, along with some ideas about what Apple hopes to accomplish.

Why were we using Objective-C?

When NeXT began, object-oriented programming hadn’t been widely adopted, and few languages available even implemented it. At the time, then, Objective-C probably seemed like a good choice, one that could incorporate legacy C code and programming habits while adding a layer of object orientation on top.

FURTHER READING

APPLE SHOWS OFF SWIFT, ITS NEW PROGRAMMING LANGUAGE
Successor to Objective C has “none of the baggage of C.”
But as it turned out, NeXT was the only major organization to adopt the language. This had some positive aspects, as the company was able to build its entire development environment around the strengths of Objective-C. In turn, anyone who bought in to developing in the language ended up using NeXT’s approach. For instance, many “language features” of Objective-C aren’t actually language features at all; they are implemented by NeXT’s base class, NSObject. And some of the design patterns in Cocoa, like the existence of delegates, require the language introspection features of Objective-C, which were used to safely determine if an object will respond to a specific message.

The downside of narrow Objective-C adoption was that it forced the language into a niche. When Apple inherited Objective-C, it immediately set about giving developers an alternative in the form of the Carbon libraries, since these enabled a more traditional approach to Mac development.

Things changed with the runaway popularity of the iPhone SDK, which only allowed development in Objective-C. Suddenly, a lot of developers used Objective-C, and many of them already had extensive experience in other programming languages. This was great for Apple, but it caused a bit of strain. Not every developer was entirely happy with Objective-C as a language, and Apple then compounded this problem by announcing that the future of Mac development was Cocoa, the Objective-C frameworks.

What’s wrong with Objective-C?

Objective-C has served Apple incredibly well. By controlling the runtime and writing its own compiler, the company has been able to stave off some of the language limitations it inherited from NeXT and add new features, like properties, a garbage collector, and the garbage collector’s replacement, Automatic Reference Counting.

But some things really couldn’t be changed. Because it was basically C with a few extensions, Objective-C was limited to using C’s method of keeping track of complex objects: pointers, which are essentially the memory address occupied by the first byte of an object. Everything, from an instance of NSString to the most complex table view, was passed around and messaged using its pointer.

For the most part, this didn’t pose problems. It was generally possible to write complex applications without ever being reminded that everything you were doing involved pointers. But it was also possible to screw up and try to access the wrong address in memory, causing a program to crash or opening a security hole. The same holds true for a variety of other features of C; developers either had to do careful bounds and length checking or their code could wander off into random places in memory.

Beyond such pedestrian problems, Objective-C simply began showing its age. Over time, other languages adopted some great features that were difficult to graft back onto a language like C. One example is what’s termed a “generic.” In C, if you want to do the same math with integers and floating point values, you have to write a separate function for each—and other functions for unsigned long integers, double-precision floating points, etc. With generics, you can write a single function that handles everything the compiler recognizes as a number.

Apple clearly could add some significant features to the Objective-C syntax—closures are one example—but it’s not clear that it could have added everything it wanted. And the very nature of C meant that the language would always be inherently unsafe, with stability and security open to compromise by a single sloppy coder. Something had to change.

But why not take the easy route and adopt another existing language? Because of the close relationship between Objective-C and the Cocoa frameworks, Objective-C enabled the sorts of design patterns that made the frameworks effective. Most of the existing, mainstream alternatives didn’t provide such a neat fit for the existing Cocoa frameworks. Hence, Swift.

Is it any good?

Swift isn’t a radical departure in many ways. Apple likes certain design patterns, and it constructed Objective-C and Cocoa to encourage them. Swift does the same thing, going further toward formalizing some of the patterns that have been adopted in a somewhat haphazard way (like properties). Most of the features Swift adds already exist in other programming languages, and these will be familiar to many developers. The features that have been added are generally good ones, while the things that have been taken away (like pointer math) were generally best avoided anyway.

In that sense, Swift is a nice, largely incremental change from Objective-C. All the significant changes are in the basic syntax. Use semicolons and parentheses—or don’t, it doesn’t matter. Include the method signature in the function call—but only if you feel like it. In these and many other cases, Swift lets you choose a syntax and style you’re comfortable with, in many cases allowing you to minimize typing if you choose to.

Most of the new features have been used in other languages, the syntax changes get rid of a lot of Objective-C’s distinctiveness, and you’re often able to write equivalent code using very different syntax. All of this enables Swift to look familiar to a lot of people who are familiar with other languages. That sort of rapport has become more important as Apple attracts developers who’d never even touched C before. These people will still have to learn to work with the design patterns of Apple’s frameworks, but at least they won’t be facing a language that’s intimidatingly foreign at the same time.

In general, these things seem like positives. If Apple chose a single style, then chances were good that a number of its choices wouldn’t be ones we’d favor. But with the flexibility, we’ll still be able to work close to the way we’d want.

Close, but not exactly. There are a couple of specific syntax features I’m personally not a fan of and a number of cases where a single character can make a radical difference to the meaning of a line of code. Combined, the syntax changes could make managing large projects and multiple developers harder than it has been with Objective-C.

What’s Apple up to?

For starters, it’s doing the obvious. Swift makes a lot of common errors harder and a number of bad practices impossible. If you choose, you can write code in Swift pretty tersely, which should make things easier for developers. It adds some nice new features that should make said developers more productive. All of those are good things.

More generally, though, Apple is probably mildly annoyed with people like me. I spent time getting good at using autorelease pools, my apps didn’t leak memory, and I didn’t see the point in learning the vagaries of the syntax required to make sure Automatic Reference Counting didn’t end up with circular references that couldn’t be reclaimed. I wasn’t a huge fan of the dot notation for accessing properties, so I only used it when it couldn’t be avoided. In short, I was a dinosaur in waiting.

People like me are why the runtime and compiler teams can’t have nice things. If everybody’s using the same features, it’s easier to get rid of legacy support and optimize the hell out of everything that’s left. A smaller memory footprint and better performance mean lower component costs and better battery life, which are very good things for the company.

Apple promised better performance with Swift, and you can see some places where it might extract a bit. Constants are a big part of Swift, which makes sense. If you make a stock-tracking app, the price may change every second, but the stock’s name and symbol change so rarely that it’s just as easy to make a whole new object when this happens. Declare the name and symbol constants, and you can skip all the code required to change them in a thread-safe manner. Presumably, the compiler can manage some optimizations around the use of constants as well.

Unlike the dinosaurs, we can see Chicxulub coming. Two or three years from now, when Apple announces that the future is Swift and it’s ready to drop Objective-C, we won’t be at all surprised. And I won’t be at all upset, because I’ll have spent the intervening few years making sure I know how to use the new language.

ios App installation over the air with http/S

Getting “Cannot install applications because the certificate is not valid” error on iOS?

Cause:

With the launch of iOS 7.1, Apple requires the enterprise apps manifest file (.plist) to be served over HTTPS. Attempts to install through HTTP cause the above message.

A change was introduced to iOS as of iOS 7.1 that requires OTA application installation to take place over HTTPS (rather than HTTP), and no provision exists to allow the user to continue to accept the old behavior (i.e., to permit application installation over HTTP). It is my understanding that this was done as a security enhancement.

Solution:

In order to do application installations on iOS 7.1 from Application Center, you would need to configure your Application Center to use HTTPS rather than HTTP, using a certificate that will be accepted as valid by your iOS device – that is, either issued by a recognized public CA, or issued by a private CA that you have set up your mobile devices to accept.

Nearly five million jobs in European app sector by 2018 – EU report

The European Union’s (EU) app sector has gone from zero to digital superhero in less than five years and by 2018 it could employ 4.8 million people and contribute €63bn to the EU economy, according to a report presented in Brussels today.

Today the app economy employs a million developers, and 800,000 people in marketing and support posts. This could rise to 2.7 million developers over 2.1 million support staff by 2018.

EU buyers and advertisers spent €6.1bn on apps in 2013, 30pc of total global app spending, growing to €18.7bn in 2018.

Consumer spending combined with advertising and contract work could lead to €63bn annual revenue for the app sector within five years.

“In the face of increasing youth unemployment, these figures give me new hope,” said Neelie Kroes, vice-president of the European Commission.

“The app sector is one area of the digital economy where Europe can really lead. But we have to address concerns about connectivity and fragmentation – yet another reason to complete the telecom single market.”

Factory Methods alternative Vs init-alloc, new

Objects Are Created Dynamically

 

Memory is allocated dynamically for an Objective-C object. The first step in creating an object is to make sure enough memory is allocated not only for the properties defined by an object’s class, but also the properties defined on each of the superclasses in its inheritance chain.

The NSObject root class provides a class method, alloc, which handles this process for you:

+ (id)alloc;

Notice that the return type of this method is id. This is a special keyword used in Objective-C to mean “some kind of object.” It is a pointer to an object, like (NSObject *), but is special in that it doesn’t use an asterisk.

The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.

You need to combine a call to alloc with a call to init, another NSObject method:

- (id)init;

The init method is used by a class to make sure its properties have suitable initial values at creation, and is covered in more detail in the next chapter.

Note that init also returns an id.

If one method returns an object pointer, it’s possible to nest the call to that method as the receiver in a call to another method, thereby combining multiple message calls in one statement. The correct way to allocate and initialize an object is to nest the alloc call inside the call to init, like this:

    NSObject *newObject = [[NSObject alloc] init];

This example sets the newObject variable to point to a newly created NSObject instance.

The innermost call is carried out first, so the NSObject class is sent the alloc method, which returns a newly allocated NSObject instance. This returned object is then used as the receiver of the init message, which itself returns the object back to be assigned to the newObject pointer, as shown in Figure 2-5.

Figure 2-5  Nesting the alloc and init message

Initializer Methods Can Take Arguments

Some objects need to be initialized with required values. An NSNumber object, for example, must be created with the numeric value it needs to represent.

The NSNumber class defines several initializers, including:

- (id)initWithBool:(BOOL)value;
- (id)initWithFloat:(float)value;
- (id)initWithInt:(int)value;
- (id)initWithLong:(long)value;

Initialization methods with arguments are called in just the same way as plain init methods—an NSNumber object is allocated and initialized like this:

    NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];

Class Factory Methods Are an Alternative to Allocation and Initialization

As mentioned in the previous chapter, a class can also define factory methods. Factory methods offer an alternative to the traditional alloc] init]process, without the need to nest two methods.

The NSNumber class defines several class factory methods to match its initializers, including:

+ (NSNumber *)numberWithBool:(BOOL)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithLong:(long)value;

A factory method is used like this:

    NSNumber *magicNumber = [NSNumber numberWithInt:42];

This is effectively the same as the previous example using alloc] initWithInt:]. Class factory methods usually just call straight through to alloc and the relevant init method, and are provided for convenience.

Use new to Create an Object If No Arguments Are Needed for Initialization

It’s also possible to create an instance of a class using the new class method. This method is provided by NSObject and doesn’t need to be overridden in your own subclasses.

It’s effectively the same as calling alloc and init with no arguments:

    XYZObject *object = [XYZObject new];
    // is effectively the same as:
    XYZObject *object = [[XYZObject alloc] init];

Literals Offer a Concise Object-Creation Syntax

Some classes allow you to use a more concise, literal syntax to create instances.

You can create an NSString instance, for example, using a special literal notation, like this:

    NSString *someString = @"Hello, World!";

This is effectively the same as allocating and initializing an NSString or using one of its class factory methods:

    NSString *someString = [NSString stringWithCString:"Hello, World!"
                                              encoding:NSUTF8StringEncoding];

The NSNumber class also allows a variety of literals:

    NSNumber *myBOOL = @YES;
    NSNumber *myFloat = @3.14f;
    NSNumber *myInt = @42;
    NSNumber *myLong = @42L;

Again, each of these examples is effectively the same as using the relevant initializer or a class factory method.

You can also create an NSNumber using a boxed expression, like this:

    NSNumber *myInt = @(84 / 2);

In this case, the expression is evaluated, and an NSNumber instance created with the result.

Objective-C also supports literals to create immutable NSArray and NSDictionary objects;