Easily share code snippets quickly

An Integrated Development Environment (IDE) is quite a powerful instrument as an online application for quickly composing and sharing code snippets through a natural, intuitive and handy interface. The latter offers live previews and separate windows for CSS, HTML and JS, as well as includes numerous helpful instruments such as pre-installed JavaScript libraries, support for pre-processors languages, code generator, tools for collaborative work and others.

We have compiled a list of outstanding places to share code snippets quickly. So if you are dying to get started, just select the best medium for you.

Codepad : [https://codepad.co/]

Screen Shot 2016-08-13 at 2.23.14 PM

Codepad is a new platform that is well-suited to developers of various spheres. Whether you are specializing in ActionScript or C-Sharp, the service will suit you up with a handy environment for writing, testing, saving and sharing your code snippets online.

Depending on the task, you can create public, private and part-private snippets as well as gather all the projects under one roof thereby compiling a collection.

With an active community, you can also follow fellow developers, find out new solutions and get inspired by other creations.

GitHub Gist

Screen Shot 2016-08-13 at 2.22.42 PM

Much like the previous example, GitHub Gist is one of the preferred choices among developers when it comes to building open-source projects. You can create public or secret gits, accompany each code snippet with the documentation or helpful instructions, and update it whenever you need to. What’s more, anyone can comment or fav it.

Codeshare

Screen Shot 2016-08-13 at 2.27.32 PM

Codeshare is another “no-sign-up-required” frontend editor that offers developers a handy playground with an intuitive interface and a small set of valuable tools. Simply write or paste code, share a link with colleagues and discuss and solve a problem together. Moreover, there is a video chat powered by WebRTC to collaborate in real-time. The only drawback is that your project will disappear from the server in 14 days.

jsFiddle

Screen Shot 2016-08-13 at 2.32.23 PM.png

jsFiddle gets straight to the point. Being one of the first in this area, it carved a niche for itself a long time ago. There is no welcoming landing page that highlights features of the playground or shows the work of others; however it does what it should do – provide coders with the smart board to mix and match various techniques to achieve the desired result.

The homepage is broken into four sections where you can write in HTML, CSS, and JavaScript and see the effect in real time. It has several particular qualities such as:

  • Typescript support
  • Auto-saving for local drafts
  • JavaScript libraries
  • Collaboration tools for teams
  • Intuitive and efficient way to generate embed code and more

CSSDeck

Screen Shot 2016-08-13 at 2.34.11 PM.png

With more than 50,000 registered members, CSSDeck is a leading platform for writing and sharing source code. Although the nameplate suggests that it is concentrated with CSS, you can build concepts that are centered around HTML and JavaScript.

You do not have to own an account to get down to business. Nevertheless, if you want to enjoy all the perks, you’d better create one, and it is entirely free.

Original Post : Please click here

Thanks Friends

Keep Coding 🙂

SolutionsPoint

 

Advertisements

AngularJS vs. Backbone.js vs. Ember.js

1 Introduction

In this article we are going to compare three popular MV* frameworks for the web: AngularJS vs. Backbone vs. Ember. Choosing the right framework for your project can have a huge impact on your ability to deliver on time, and your ability to maintain your code in the future. You probably want a solid, stable and proven framework to build upon, but don’t want to be limited by your choice. The web is evolving fast — new technologies arise, and old methodologies quickly become irrelevant. Under this light, we are going to go through an in-depth comparison of the three frameworks.

2 Meet The Frameworks

All the frameworks we are going to meet today have a lot in common: they are open-sourced, released under the permissive MIT license, and try to solve the problem of creating Single Page Web Applications using the MV* design pattern. They all have the concept of views, events, data models and routing. We are going to start with some quick background and history, and then dive in to compare the three frameworks.

AngularJS was born in 2009 as a part of a larger commercial product, called GetAngular. Shortly after, Misko Hevery, one of the engineers who founded GetAngular, managed to recreate a web application that consisted of 17 thousand lines of code and took 6 months to develop in a mere 3 weeks using just GetAngular. Reducing the size of the application to just about 1,000 lines of code convinced Google to start sponsoring the project, turning it into the open-source AngularJS we know today. Amongst Angular’s unique and innovative features are two-way data bindings, dependency injection, easy-to-test code and extending the HTML dialect by using directives.

Backbone.js is a lightweight MVC framework. Born in 2010, it quickly grew popular as a lean alternative to heavy, full-featured MVC frameworks such as ExtJS. This resulted in many services adopting it, including Pinterest, Flixster, AirBNB and others.

Ember’s roots go way back to 2007. Starting its life as the SproutCore MVC framework, originally developed by SproutIt and later by Apple, it was forked in 2011 by Yehuda Katz, a core contributor to the popular jQuery and Ruby on Rails projects. Notable Ember users include Yahoo!, Groupon, and ZenDesk.

3 Community

Community is one of the most important factors to consider when choosing a framework. A large community means more questions answered, more third-party modules, more YouTube tutorials…you get the point. I have put together a table with the numbers, as of June 30, 2015. Angular is definitely the winner here, being the 3rd most-starred project on GitHub and having more questions on StackOverflow than Ember and Backbone combined, as you can see below:

 

Metric AngularJS Backbone.js Ember.js
Stars on Github 40.2k 18.8k 14.1k
Third-Party Modules 1488 ngmodules 256 backplugs 1155 emberaddons
StackOverflow Questions 104k 18.2k 15.7k
YouTube Results ~93k ~10.6k ~9.1k
GitHub Contributors 96 265 501
Chrome Extension Users 275k 15.6k 66k
Open Issues 922 13 413
Closed Issues 5,520 2,062 3,350

All those metrics, however, merely show the current state of each framework. It is also interesting to see which framework has a faster-growing popularity. Fortunately, using Google Trends we can get an answer for that too:

4 Framework Size

Page load times are crucial for the success of your web site. Users do not exhibit much patience when it comes to the speed of browsing — so in many cases it is desired to do everything possible to make your application load as fast as possible. There are two factors to look at when considering the impact of the framework on the loading time of your application: framework size and the time it takes the framework to bootstrap.

Javascript assets are usually served minified and gzipped, so we are going to compare the size of the minified-gzipped versions. However, merely looking at the framework is not enough. Backbone.js, despite being the smallest (only 6.5kb), requires both Underscore.js (5kb) and jQuery (32kb) or Zepto (9.1kb), and you will probably need to add some third party plug-ins to the mix.

Framework Net Size Size with required dependencies
AngularJS 1.2.22 39.5kb 39.5kb
Backbone.js 1.1.2 6.5kb 43.5kb (jQuery + Underscore)
20.6kb (Zepto + Underscore)
Ember.js 1.6.1 90kb 136.2kb (jQuery + Handlebars)

5 Templating

Angular and Ember include a template engine. Backbone, on the other hand, leaves it up to you to use the template engine of your choice. The best way to get a feeling of the different templating engines is a code sample, so let’s dive in. We will show an example of formatting a list of items as HTML.

5.1 AngularJS

Angular’s Templating engine is simply HTML with binding expressions baked-in. Binding expressions are surrounded by double curly braces:

<ul> 
    <li ng-repeat="framework in frameworks" title="{{framework.description}}">               
                  {{framework.name}} 
    </li> 
</ul>

5.2 Backbone.js

While Backbone can be integrated with many third-party template engines, the default choice is Underscore templates. Since Underscore is a Backbone dependency and you already have it on your page, you can easily take advantage of its templating engine without adding any additional dependencies for your application. On the downside, the templating engine of Underscore is very basic and you usually have to throw javascript into the mix, as you can see in our example:

<ul> 
    <% _.each(frameworks, function(framework) { %> 
        <li title="<%- framework.description %>"> 
            <%- framework.name %> 
        </li> 
    <% }); %> 
</ul>

5.3 Ember.js

Ember currently uses the Handlebars template engine, which is an extension to thepopular Mustache templating engine. A new Handlebars variant, called HTMLBars is currently in the works. Handlebars does not understand DOM – all it does is a simple string transformation. HTMLBars will understand DOM, so the variable interpolation will be context aware. As HTMLBars is still not production-ready, we will show the Handlebars way of printing the framework list:

<ul> 
    {{#each frameworks}} 
        <li {{bind-attr title=description}}> 
            {{name}} 
        </li> 
    {{/each}} 
</ul>

6 AngularJS

6.1 The Good Parts

Angular has brought many innovative concepts to the world of web developers. Two-way data binding saves a lot of boilerplate code. Consider the following jQuery code snippet:

$('#greet-form input.user-name').on('value', function() { 
    $('#greet-form div.user-name').text('Hello ' + this.val() + '!'); 
});

Thanks to Angular’s two-way-binding, you never have to write this code yourself. Rather, you just declare the bindings in your HTML template:

<input ng-model="user.name" type="text" />
Hello {{user.name}}!

Promises play a main role in the Angular cast. Javascript is a single-thread, event-loop based language, which implies that many operations (such as network communication) happen in an asynchronous manner. Asynchronous javascript code tends to grow quickly into a spaghetti of nested callbacks, better recognized as “Pyramid Code” or “Callback Hell.”

Not only does Angular have the largest community and much more online content than the two others, it is also backed and promoted by Google. As such, the core team is constantly growing, resulting in innovation and tools that improve developer productivity: Protractor, Batarang, ngmin and Zone.js, just to name a few. In addition, the team collaborates with the community on the design decisions. For example, all the design documents for Angular 2.0 can be found here, and everyone can make suggestions directly to the design documents.

Angular helps you categorize your application building blocks into several types: Controllers, Directives, Factories, Filters, Services and Views (templates). Those are organized in turn into modules, which can depend one upon the other. Each type of building block has a different role. Views do the UI, Controllers work out the logic behind the UI, Services take care of communication with the backend and hold together pieces of common and related functionality, while Directives make it easy to create reusable components and extending HTML by defining new elements, attributes and behaviors.

The automatic Dirty Checking means that you don’t have to access your model data with getters and setters — you can modify any property of an arbitrary scope object and angular will automatically detect the change and notify all the watchers for that property.

“Angular is written with testability in mind.” This quote from the unit-testing guide has a lot behind it – Angular indeed puts a lot of emphasis on separation of concerns, unit isolation and provides ready-to-use, powerful mocks for fundamental built-in services such as $http and $timeout.

6.2 Pain Points

Angular is often criticized for the complexity of the Directives API. Transclusion, in particular, is a concept which confuses many developers and wrapping your head around all the concepts such as compiling function, pre/post linking functions, the different scope kinds (transclusion/isolate/child scope) and all the other configuration settings for directives takes some time to master.

The scope hierarchy in Angular uses Prototypal Inheritance, which is a new concept to grasp for people coming from Object Oriented languages such as Java and C#. Failing to understand scope inheritance causes many cases of frustrated developers (examples: here, here and here).

Angular Expressions are used extensively in the View layer of Angular. This expression language is very powerful, sometimes too powerful. It lets the developer use complicated logic and even perform assignment operations and calculations, all inside the view templates. Putting logic inside the templates makes it harder to test, as it becomes impossible to test it in isolation. Consider the following code example, which clearly shows how easily the template language can be abused:

<button ng-click="(oldPassword && checkComplexity(newPassword) && oldPassword != newPassword) ? (changePassword(oldPassword, newPassword) && (oldPassword=(newPassword=''))) : (errorMessage='Please input a new password matching the following requirements: ' + passwordRequirements)">Click me</button>

In many cases, mistakes such as misspelling a directive name or calling an undefined scope function are silently ignored and can be challenging to find, especially when you throw into the mix the complexity of the directive API and the scope inheritance mentioned above. I have seen developers spending hours scratching their head trying to figure out why an event binding didn’t fire the callback function on the scope, only to find out they have used the camelCase convention instead of the hyphen-separated one when spelling attribute names (example here).

Finally, the Digest Cycle of angular, which takes care of the “Magical” dirty checking, has the tendency to surprise developers. It is easy to forget to call $digest() when running in non-Angular context (example). On the other hand, you have to be very careful not to cause slow watches or infinite digest loops (examples: here, here andhere). In general, for pages with a lot of interactive elements, Angular becomes really slow. A good rule of thumb is not to have more than 2,000 active bindings on the same page.

7 Backbone.js

7.1 The Good Parts

Backbone is lightweight, fast and has a small memory footprint. The learning curve is very linear, and there are only a few simple concepts to grasp (Models/Collections, Views, Routes). It has great documentation, the code is simple and heavily documented, and there is even an annotated version of the code which explains how it works in detail. You can actually go over the entire source code of the framework and get familiar with it in less than an hour.

Being so small and basic, Backbone can be a good foundation to build your own framework upon. Some examples of 3rd party frameworks based on Backbone are Aura, Backbone UI, Chaplin, Geppetto, Marionette, LayoutManager, Thorax, Vertebrae. With Angular and Ember you usually have to live with the choices made by the authors of the frameworks, which may or may not suit your project needs and personal style. Angular 2.0 promises to change it, by comprising small independent modules, so you will be able to pick and mix. We are yet to see if they will be able to deliver this.

7.2 Pain Points

Backbone does not provide structure. It rather provides some basic tools you can use to create structure, leaving it up to the developer to decide how to structure his application, and there are also many blanks to fill. Things such as memory management have to be carefully considered. The lack of view lifecycle management makes route/state changes prone to memory leaks unless you take care of cleaning up everything yourself.

While it is true that many of the functions not provided by Backbone itself could be filled by third-party plugins, this also means that there are many choices to be made when creating an application, as many functions have several alternative plugins. For example, nested models can be provided by Backbone.DocumentModel, BackBone.NestedTypes, Backbone.Schema, Backbone-Nested, backbone-nestify, just to name a few. Deciding which one is the best for your project requires research, which in turn takes time — and one of the main purposes of framework is to save you time.

Backbone lacks support for two-way data binding, meaning you will have to write a lot of boilerplate to update the view whenever your model changes, and to update your model whenever the view changes. See the example given above, showing how two-way in Angular.js data binding reduces boilerplate.

Views in Backbone manipulate the DOM directly, making them really hard to unit-test, more fragile and less reusable. The common practice is to look up DOM elements using CSS selectors, so changing a CSS class name, adding a new element with the same class name or even wrapping some DOM tree inside another element can break your CSS selectors and render your app unusable.

8 Ember.js

8.1 The Good Parts

Ember.js favors Convention over Configuration. This means that instead of writing a lot of boilerplate code, Ember can automatically infer much of the configuration itself, such as automatically determining the name of the route and the controller when defining a router resource. Ember even raises the bar by automatically creating the controller for your resource if you don’t define one yourself.

Ember includes both an excellent router and an optional data layer, called ember data. Unlike the two other frameworks, which have a very minimal data layer (Backbone’s Collection/Model and Angular’s $resource), Ember comes out of the box with a fully-fledged data module which integrates really nicely with a Ruby-on-Rails backend or any other RESTful JSON API that follows a simple set of conventions. It also provides support for setting up fixtures for developing against mock API and testing.

Performance has been a major goal in the design of Ember.js. Concepts such as The Run Loop, which ensures that updated data only causes a single DOM update even if the same piece of data was updated several times, along with caching of computed properties, and the ability to precompile the HandleBars templates during the build time or on your server, help to keep your application load and run fast.

8.2 Pain Points

Ember’s API changed much before it stabilized. Therefore, there is a lot of outdated content and examples that no longer work, making it confusing for developers who are making their first steps in the framework. Take a look at the Ember Data Changelog, and you will see what I mean. There are so many breaking changes, and those cause many StackOverflow answers and coding tutorials to become irrelevant (example here).

Handlebars pollutes the DOM with many <script> tags which it uses as markers tokeep the templates up to date with your model. This will be gone with the transition to HTMLBars, but for the time being, your DOM tree will be filled up with so many<script> tags you will barely be able to recognize your own code. And the worst part – this can also break your CSS styling or integration with other frameworks, such as jQuery UI’s Sortable.

9 Summary

We have seen the strengths and weaknesses of all the three frameworks. Ember’s holistic approach which embraces MVC structure will make a lot of sense for developers who have a MVC programming background in Ruby, Python, Java, C# or any other Object Oriented language. Ember also brings application performance to the table, and excels at saving you from writing boilerplate by favoring convention over configuration.

Backbone embraces minimalism. It is small, fast and easy to learn, and provides the minimum (or in many cases, even less than the minimum) that you need to get going.

Angular’s innovative approach for extending HTML will make a lot of sense for people who are web developers in soul. With a large community and Google behind it, it is here to stay and grow, and it works well both for quick prototyping projects and large-scale production applications.

Original Reference: Click Here

Thanks, and Keep Coding

Mishra Vinay

Solution’s Point

iDev: Apple ResearchKit Turns iPhones Into Medical Diagnostic Devices

iDev: Apple ResearchKit Turns iPhones Into Medical Diagnostic Devices by

Medical research is plagued by small sample sizes and inconsistent data collection. So Apple is stepping up to help health innovation with Research Kit, a new iOS software framework that lets people volunteer to join medical research studies. ResearchKit lets people take tests like saying “ahhh” to detect vocal variations, walking in a line, or tapping in rhythm to test for Parkinson’s Disease.

Users will decide how to share their data and Apple won’t see it. And to advance its evolution, ResearchKit will be open source. ResearchKit will be available next month, and the first five tests built with it will become available today. They help people participate in tests for Parkinson’s, diabetes, cardiovascular disease, asthma, and breast cancer.

Tap Test

Apple’s Jeff Williams came out on stage today at the Apple Watch event to show off ResearchKit. He explained how Apple worked with 12 research institutions to build out the app, including University Of Oxford and Stanford.

Apple learned about some of the biggest obstacles to scientific research in medicine. Finding and recruiting subjects can be tough. Paper flyers on college campuses are one of the few ways labs sign up human guinea pigs. This obstacle can lead to small sample sizes more vulnerable to inaccuracy, and less diverse samples that might not be generalizable to the world population.

Screen Shot 2015-03-09 at 10.39.04 AM

5 ResearchKit Apps

With ResearchKit, researchers can build out a medical testing app for iOS that’s accessible to people far from their physical lab. Users can signup with a digital signature, and instantly start recording data.

Screen Shot 2015-03-09 at 10.56.38 AM

Tests designed with ResearchKit use the iPhone’s sensors to record data. The touch screen can feel people tapping in rhythm to detect inconsistencies that may signal a disease. The accelerometer can compare the gait and balance of someone’s walk against a healthy person’s speed and posture. And the microphone can notice minute fluctuations in someone’s voice that may indicate Parkinson’s or another health problem.

Gait Test
Ahh

Williams stressed the immediate benefit to users because they’re learn about their health even before a researcher’s study concludes and they publish the results. If a user notices they are having trouble balancing while walking a line, they can talk to their doctor about it.

Since medical data is obviously sensitive, Apple won’t see anything you put into ResearchKit apps and you can give permissions for how data is used by researchers.

The question will be how many developers jump aboard the ResearchKit. While it obviously holds potential improvements, it also takes time to develop traditional lab studies into an app. ResearchKit is a valiant effort by Apple, and if its a hit with scientists, it could make mass medical research easier than ever.

Original Blog Source : Click Here

iDev: Design Patterns

Creation Design Patterns in Cocoa Touch Framework

Christopher Alexander, a noted design architect, defined design pattern as:

Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.

This blog lists some well-known examples for 5 Creational Design Patterns as applicable in Cocoa Touch Framework

Creational design patterns specifically target the problems of how an object is created and instantiated. These patterns were originally described in the Gang of Four (GoF) book on Design Patterns which is regarded as an important source for object-oriented design theory and practice. 

1. Abstract Factory 

The intent of Abstract Factory design pattern as specified in GoF is: 

Provide an interface for creating families of related or dependent objects without 

specifying their concrete classes.

We use Abstract Method pattern to create objects when we want to provide a class library of products, and we want to reveal just their interfaces, not their implementations. So the system is independent of how its products are created and represented.

The Abstract Factory pattern is commonly seen in the Cocoa Touch Framework and a lot of Foundation classes have used the pattern.

The interface declared by the abstract superclass, NSNumber in Foundation Framework serves a good example for this design pattern. 

 Consider these messages:

NSNumber *aChar = [NSNumber numberWithChar:’a’];

NSNumber *anInt = [NSNumber numberWithInt:1];

NSNumber *aFloat = [NSNumber numberWithFloat:1.0];

NSNumber *aDouble = [NSNumber numberWithDouble:1.0]; 

Each returned object — aChar, anInt, aFloat, and aDouble  share a common public interface which is the interface declared by the abstract superclass, NSNumber.

@interface NSNumber : NSValue

 – (char)charValue;

– (int)intValue;

– (float)floatValue;

– (double)doubleValue;

.

@end

@interface NSNumber (NSNumberCreation)

+ (NSNumber *)numberWithChar:(char)value;

+ (NSNumber *)numberWithInt:(int)value;

+ (NSNumber *)numberWithFloat:(float)value;

+ (NSNumber *)numberWithDouble:(double)value;

@end 

but each object returned by the factory methods (numberWithChar, numberWithInt) belong to a different private subclass which is hidden to users. 

On a side note, NSNumber is also a “class cluster”. Class clusters are based on the Abstract Factory design pattern as discussed in “Cocoa Design Patterns.”

2. Factory Method

The intent of Factory Method design pattern as provided in GoF is:  

Define an interface for creating an object, but let subclasses decide which class 

to instantiate. 

We use the Factory Method pattern when a class wants its subclasses to specify the objects it creates. 

As an example, again consider NSNumber class in the Foundation framework which defines several class factory methods:

+ numberWithBool:

+ numberWithChar:

+ numberWithDouble:

+ numberWithFloat:

+ numberWithInt:

+ numberWithInteger:

+ numberWithLong:

+ numberWithLongLong:

+ numberWithShort:

+ numberWithUnsignedChar:

+ numberWithUnsignedInt:

+ numberWithUnsignedInteger:

+ numberWithUnsignedLong:

+ numberWithUnsignedLongLong:

+ numberWithUnsignedShort: 

These methods combine the two steps of allocating and initializing to return new, initialized instances of the class which are returned by the subclasses of the class where they are declared.

Having mentioned both Factory Method and Abstract Factory Method patterns, it is sometimes difficult to differentiate between the two. If we revisit the example for NSNumber class, in Factory Method pattern, we have a factory that creates objects that derive from a particular base class. So considering this example,

 NSNumber aNum = [NSNumber numberWithInt:1];

Here numberWithInt is the “factory” that allocates, initializes, and returns the “product object “ aNum

while in Abstract Factory pattern we have a factory that creates other factories, and these factories in turn create objects derived from base classes. In other word, in this example, the methods of the NSNumber Abstract Factory are implemented as Factory Methods. 

 3. Prototype

As per GoF, sometimes when instances of a class can have one of only a few different combinations of state it it is more convenient to have a corresponding number of prototypes and reuse them rather than creating the class each time with the appropriate state.

Under this scenario, it advises us to use Prototype Design Pattern. This applicability reminds us of the prototype cells we use in UITableView.

 As per Apple developer guide:

Use dynamic prototypes to design one cell and then use it as the template for other cells in the table. Use a dynamic prototype when multiple cells in a table should use the same layout to display information. 

Consider this example:

#define FIRST_LABEL_TAG 1

#define SECOND_LABEL_TAG 2

#define PHOTO_TAG 3

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @”ImageOnRightCell”; 

    UILabel *firstLabel, *secondLabel;

    UIImageView *photo;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

         if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]];

        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

        firstLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)]];

        firstLabel.tag = FIRST_LABEL_TAG;

        firstLabel.font = [UIFont systemFontOfSize:14.0];

        firstLabel.textAlignment = UITextAlignmentRight;

        firstLabel.textColor = [UIColor blackColor];

        [cell.contentView addSubview:firstLabel];

 

        secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 20.0, 220.0, 25.0)]];

        secondLabel.tag = SECOND_LABEL_TAG;

        secondLabel.font = [UIFont systemFontOfSize:12.0];

        secondLabel.textAlignment = UITextAlignmentRight;

        secondLabel.textColor = [UIColor darkGrayColor];

        [cell.contentView addSubview:secondLabel];

        photo = [[[UIImageView alloc] initWithFrame:CGRectMake(225.0, 0.0, 80.0, 45.0)]];

        photo.tag = PHOTO_TAG;

        photo.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;

        [cell.contentView addSubview:photo];

  } else {

        firstLabel = (UILabel *)[cell.contentView viewWithTag:FIRST_LABEL_TAG];

        secondLabel = (UILabel *)[cell.contentView viewWithTag:SECOND_LABEL_TAG];

        photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];

    }

    NSDictionary *aDict = [self.list objectAtIndex:indexPath.row];

    firstLabel.text = [aDict objectForKey:@”mainTitleKey”];

    secondLabel.text = [aDict objectForKey:@”secondaryTitleKey”];

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:[aDict objectForKey:@”imageKey”] ofType:@”png”];

    UIImage *theImage = [UIImage imageWithContentsOfFile:imagePath];

    photo.image = theImage;

    return cell;

}

Here we create a prototype for a cell in – tableView:cellForRowAtIndexPath: method as follows:

We create an instance of UITableViewCell and assign it a reuseIdentifier 

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]];

 We then add subviews to it based on our design

 [cell.contentView addSubview:firstLabel];

.

. 

[cell.contentView addSubview:secondLabel];

.

.

[cell.contentView addSubview:photo]; 

This prototype is now ready, and we use use this fully initialised cell as a prototype for other cells in our table view. 

 – tableView:cellForRowAtIndexPath: method first tries to acquire a cell by using dequeueReusableCellWithIdentifier.If a cell is not yet created, it creates it by using the prototype cell we had defined.

4. Singleton 

The intent of Singleton design pattern as provided in GoF is:  

Ensure a class only has one instance, and provide a global point of access to it. 

Regarding ‘Applicability’, the book states to use the Singleton pattern when

There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point

 Some common scenarios when we use Singletons in the Cocoa Touch Framework are

a. When an application is launched, the UIApplicationMain function (we can find it in main.m class in our project) is called and it creates a singleton UIApplication object. UIApplication class provides a centralized point of control for an iOS application. We can access this singleton object from any class in our project by invoking the sharedApplication class method:

 UIApplication *applicationSingleton = [UIApplication sharedApplication];

b. UIAccerometer’s sharedAccelerometer class method returns the the singleton shared accelerometer object for the system:

UIAccelerometer *accelerometerSingleton = [UIAccelerometer sharedAccelerometer];

5. Builder 

The intent of Builder design pattern as provided in GoF is:  

Separate the construction of a complex object from its representation so that 

the same construction process can create different representations. 

Unlike creational patterns that construct objects in one go, the Builder pattern constructs the object step by step. It is used in creation of a complex object. 

The builder pattern is not too much adopted in Objective-C as in java. Eric Buck, author ofCocoa Design Patterns, in one of his interview has said

“I think all of the famous GoF patterns exist within Cocoa, but many are either trivially implemented or made less necessary thanks to Objective-C. For example, the Cocoa convention of two stage allocation and initialization makes the GoF Abstract factory and Builder patterns trivial.”

In one flavor, as described in the book – Learn Objective-C for Java Developerscategories can be used for Builder Pattern in Objective C. The complex construction code is isolated from the main class definition via a category.

Summary

We saw how Cocoa Touch Framework uses different creational design patterns to create objects and their intent behind choosing a particular design pattern while creation of an object. For eg. Abstract Factory, Builder, and Prototype patterns – all 3 involve creating a new “factory object” which creates “product objects”.  But each differ the way the product objects are created – Abstract Factory factory object produces objects of several classes. Prototype has the factory object building a product by copying a prototype object while Builder has the factory object building a complex product incrementally. 

This blog listed only the design patterns used in the creation of objects. There are also structural and behavioral design patterns. It is always good to have a knowledge of wide variety of design patterns and the intent behind the use of a particular design pattern.

This helps us to leverage the knowledge of our industry experts and reuse it in our application design. Of course, the applicability of a particular design pattern depends on various factors. We must carefully choose from different design patterns. Understanding how the Cocoa Touch Framework uses these patterns, gives us a fair idea about their usage.

Source: Press Here

 Thanks 🙂

Solutions Point:)

Keep Coding 🙂

 

The 18 Most Important Features in iOS 8

At WWDC, developers rule. Apple may have previewed iOS 8 and OS X Yosemite to the entire world at its opening keynote, but developers are the only ones who get to check out the beta version of the software until an open beta program kicks off this summer.

This year’s conference has had its share of surprises, and it’s little wonder devs are salivating: Apple is allowing more flexibility about what developers can grow within its walled garden. For the first time, third-party onscreen keyboards will be welcomed in iOS 8, widgets are coming to the notification center, and media apps will have greater access to the device’s camera. Apple even debuted its own programming language, Swift, which got some of the loudest cheers during Monday’s keynote.

That’s all well and good, but what about the rest of us?

What’s in iOS 8 that will change the mobile life of your everyday iPhone user?

What’s in iOS 8 that will change the mobile life of your everyday iPhone user? Quite a bit, as it turns out. Here are the most important changes coming in iOS 8, based on whatApple revealed at WWDC and reports about the beta software:

 

1. Battery usage indicator

It’s probably the most common complaint about the iPhone: The battery drains too damn fast. This is, of course, dependent on exactly what you do with it, but how do users know whether to prioritize dimming the screen, quitting a particular app or turning off Background App Refresh?

In iOS 8, they’ll finally get some guidance. The iPhone’s settings will offer a way to checkexactly which apps and functions are draining your battery. With that guidance, users will be able to selectively change their settings or uninstall the right apps to maximize their battery.

Developers will certainly find the feature useful as well, as it should help make their apps more efficient. In short, this could be the most welcome new feature in iOS 8.

2. New keyboard(s)

iOS 8 keyboard

There’s nothing more fundamental to the iPhone than its onscreen keyboard — and in iOS 8, it gets an upgrade via predictive typing, which suggests several options for the next word as you type. This is a feature that’s been on Android for a while, although Apple says its implementation is superior — since it learns what you’re likely to say to different friends and colleagues.

At the same time, Apple is letting developers offer their own keyboards. You may have tried Swype for Android, for example, which uses an algorithm that lets you swipe around a keyboard rather than tap; the company has already said it will make its keyboard available for iOS.

3. Continuity

Continuity

IMAGE: APPLE

Apple took the idea of collaboration through the cloud to a new level with a new feature called Handoff, part of its “Continuity” concept. If you have an iPhone and a Mac, you’ll be able to start a task on one device (say, composing an email) and finish on the other. Since the devices are aware of each other, all you have to do is click one button, and it works on iPad, too.

Continuity also has a couple of bonuses: First, AirDrop will work between Macs and iOS devices. Second, using your iPhone as a personal hotspot has never been easier. There’s no configuration needed — the iPhone will just know when your Mac needs the connection.

4. New camera features

The camera is probably every smartphone’s No. 1 app. Apple likes to keep its interface relatively simple, but in iOS 8, users will get a couple of more options: a three-second timerand time-lapse capture for video — sort of the opposite of the slow-motion mode introduced in iOS 7. The camera also gets focus and exposure controls.

5. iCloud Photo Library

iCloud Photo Library

iCloud currently stores the last 1,000 photos from your iOS devices for free. With iOS 8, users will be able to upgrade to iCloud Photo Library, which will instantly upload all iPhone/iPad photos and videos to iCloud. Users only get 5GB for free, though — storage costs $0.99 a month for 20GB, with tiers all the way up to 1TB. (The Google+ app on iOS, by the way, will back up all your photos up to Google’s 15 GB limit, for free).

6. Family Sharing

Family Sharing

IMAGE: MASHABLE, LANCE ULANOFF

With iOS 8, Apple is taking the first step toward merging Apple IDs (a long-requested feature) by introducing Family Sharing, which lets different Apple users share all content they’ve downloaded from iTunes. Up to six people can be designated family members, and it provides a great solution to the problem of kids downloading paid apps on their parents’ credit cards: With Family Sharing, the parent gets notified, and then can grant or deny the purchase.

7. Interactive Notifications

Interactive Notifications

IMAGE: MASHABLE, LANCE ULANOFF

Just need to reply to a message with a single word? Why do you have to launch Messages for that? In iOS 8, you won’t have to — just pull down on the banner that appears and you can type your reply — then get right back to playing Candy Crush.

Notifications on the lock screen are interactive, too. Swiping an alert to the left will reveal Reply/Dismiss buttons, letting you do things faster without unlocking your phone. And if you’re concerned about security implications, you can disable this feature.

8. Messages upgrade

iOS 8 Messages 

In iOS 8, Apple’s built-in messaging app has a lot more to offer. Apple added the ability to send audio and video messages to your friends. With audio, they’re effortless: just open the conversation and raise the phone to your ear to begin recording. Users can also let these kinds of messages self-destruct after a certain amount of time — but that’s just a memory-management feature, and not, as has been claimed, an attempt to move in on Snapchat’s territory. (After all, there’s nothing to prevent the other people in the conversation from saving their versions of the video or audio.)

At the same time, Messages adds a couple of convenient features: You can set Do Not Disturb on specific threads so you’re not constantly getting alerts from big group messages. You can also now share your location with contacts you’re conversing with, as in the Find My Friends app, viewable through a new “Details” button on threads.

9. Widgets

iOS 8 widgets

IMAGE: MASHABLE, LANCE ULANOFF

Here’s another upgrade that Android has had a lock on for years: widgets, made possible byiOS 8’s “extensibility,” which allows apps to share data and functions with other apps.

Don’t get too excited — widgets will reside in the notification center, not the home screen. But their arrival on iOS is a big upgrade, and if Android is any indication, you can expect the floodgates to open for these small, “glanceable” mini-apps when iOS 8 launches in the fall.

10. Lock screen app suggestions

In iOS 8, users will notice a new icon on the iPhone lock screen that looks like the App Store. Swipe up and you’ll see app suggestions based on your location. For example, if you’re across the street from Starbucks, you might see the Starbucks app.

The feature could be a new path to app discoverability (which can be a problem for apps not in the Top 100), but we’ll wait to see how this plays out between Apple, vendors and developers.

11. TouchID for apps

TouchID

IMAGE: MASHABLE, LANCE ULANOFF

Apple took fingerprint reading mainstream with the TouchID sensor in the iPhone 5S. In iOS 8, it’s going to open up that level of convenience to developers, who can let a user unlock any password stored in their keychain by placing their finger on the reader. That could potentially be even more convenient than Lastpass app logins on Android.

12. iCloud Drive

iCloud Drive 

If you’ve ever tried to save, say, a PDF from an email on your iPhone, you may have been frustrated by the lack of a native file system for iOS. Soon iCloud Drive will address that problem, while at the same time offering a cloud-storage service similar to Dropbox, Box or Google Drive. It’s compatible with Windows, too — but not Android.

13. Health

Health

IMAGE: APPLE

The new Health app is straightforward: It provides a central place for all the health and fitness information you’re storing on the iPhone. Many apps, such as Nike+ and Fitbit, do this individually, but now those apps will be able to integrate into one app — presuming developers take advantage of Apple’s HealthKit platform.

Apple is also partnering with healthcare providers to help bring the iPhone health data to the doctors and care specialists who can really do something with it. Health could have a profound effect on preventative medicine, if both developers and care centers support it.

14. New Siri features

Siri

IMAGE: MASHABLE, LANCE ULANOFF

Be careful what you say — Siri is always listening in iOS 8. Even if the iPhone is in a dormant state, you can just say “Hey Siri” to wake up the phone and ask something. The phone has to be plugged into power for this to work, indicating Apple probably sees it as a hands-free solution for the car.

Siri can also identify songs with built-in Shazam integration. So instead of launching an app, all you’ll need to do is hold down your iPhone’s home button to find out what music is playing. Think of all the time you’ll save at the bar.

15. Contacts on apps screen

iOS 8 Contacts

IMAGE: MASHABLE, CHRISTINA WARREN

Apple realized it wasn’t making use of all the space on the apps screen that appears when you double-click the home button. Right above the apps running, you’ll see a strip of the most recent contacts along the top. It’s another welcome convenience.

16. More Spotlight results

iOS 8 Spotlight results

IMAGE: MASHABLE, CHRISTINA WARREN

Searching on the iPhone in iOS 8 now brings up Wikipedia, App Store and iTunes results for anything you’re searching for.

17. Full-featured Safari

Safari got a huge upgrade in iOS 7, and although the upgrades in iOS 8 are more incremental (and already exist in other browsers), they’re welcome. There’s more flexibility in Private browsing, letting you keep regular and private tabs separate. DuckDuckGo — the privacy-preserving alternative to Google — is supported as a search engine, and users will be able to easily request the desktop version of any site.

18. The Weather Channel

In iOS 7, Apple’s weather app got its info from Yahoo. Starting in iOS 8, that data comes from the Weather Channel.

Have something to add to this story? Share it in the comments.

Source : Press HERE

Thanks 🙂

Solution’s Point

iDev: Copy a plist file to documents folder

Hi Friends,

Here a code snapshot for your help on Copy a plist file to Documents Folder

BOOL isSuccess;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"idevCopyData.plist"];
isSuccess = [fileManager fileExistsAtPath:filePath];
if (isSuccess) return;
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"idevCopyData.plist"];
isSuccess = [fileManager copyItemAtPath:path toPath:filePath error:&error];
if (!isSuccess) {
NSAssert1(0, @"Failed to copy Plist. Error %@", [error localizedDescription]);
}

 

Reference : Here

Thanks 🙂

 

iDev: Change iOS project “My Mac 64-bit” to “iOS Device”

Hi Friends,

XCode iOS project only shows “My Mac 64-bit”!!!

The Simulator and Device options to Build/Run your have have disappeared.
This happened to  me after I changed the project name once or changed by another person.

solution #1:

  1. – Close Xcode.
  2. – Locate your Project folder.
  3. – Right-click on the AppName.xcodeproj file and click show package contents.
  4. – Now delete everything inside the xcuserdata folder.

If this does not work trying this:

  1. – open Xcode (obviously)
  2. – clicked on Manage Schemes and then Autocreate Schemes Now.
  3. – Then select the new scheme in Xcode.

Now you should get back all device/simulator options.

Thanks 🙂

Keep Coding 🙂

iDev: Objective-C Associated Objects

Objective-C Associated Objects

Add properties to objects in categories.

As a developer, I love coming across new methods or techniques that help make better, more readable code. Recently I was trying to find a better way of passing information from a method that creates a UIAlertView to the UIAlertView’s delegate method alertView:didDismissWithButtonIndex:. There is no userInfo dictionary for an alert view, and Apple specifically says not to subclass UIAlertView. What I’ve done in the past is create a property or class instance variable to temporarily hold the object I want to pass around. I don’t like this technique, it feels sloppy, but it gets the job done. Now behold the power of Objective-C Associated Objects.

Associated Objects

Associated objects have been around since iOS 3.1 and are a part of the Objective-C runtime. They allow you to associate objects at runtime. Basically, you can attach any object to any other object without subclassing. To begin using associated objects, all you need to do is import <objc/runtime.h> in the class where you want to use them. The relevant methods are the following:

void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, void *key)
void objc_removeAssociatedObjects(id object)

object is the source object for the association, or in other words, it is the object that will point to the other object.
*key is the the key for the association, this can be any void pointer, anything that has a constant memory address is all you want.
value is the object you want to store or associate with the source object.
policy is a constant defining the type of reference, similar to the types you use when declaring properties. The possible values are:

enum {
   OBJC_ASSOCIATION_ASSIGN = 0,
   OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
   OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
   OBJC_ASSOCIATION_RETAIN = 01401,
   OBJC_ASSOCIATION_COPY = 01403
};

 

Typically we don’t want to use objc_removeAssociatedObjects, but would rather use setAssociatedObject with a nil value to remove an association. According to Apple,
The main purpose of this function is to make it easy to return an object to a “pristine state”. You should not use this function for general removal of associations from objects, since it also removes associations that other clients may have added to the object. Typically you should use objc_setAssociatedObject with a nil value to clear an association.

In many cases you probably won’t have to worry about removing an association because when the source object is destroyed it will destroy the reference to the associated object.

Sample Use Case

In my case, I want to associate an NSIndexPath to a UIAlertView. Let me explain my use case a little further, you have probably come across a similar problem. I have a table view where I show a confirmation alert when the user tries to delete a row. Usually I wouldn’t put a confirmation on a delete, but sometimes it has serious implications (maybe you’re deleting a folder holding 100 records of something and deleting the folder deletes all those precious records).

The alert is created and displayed in the UITableViewDataSource method tableView:commitEditingStyle:forRowAtIndexPath:. At this point you have the indexPath you want to delete. Once you call -show on the alert, your class starts waiting for the UIAlertViewDelegate callback methodalertView:didDismissWithButtonIndex:. Once the user confirms, it enters the delegate method and you no longer know which indexPath you should delete.

Now I’m going to detail a number of solutions to this problem, each better than the last. I’m only going to show the relevant code though instead of the entire class because I’m using a very simple example. I just slightly modified the code that is generated for you when you create a new project with the master-detail template (without core data).

Original Solution

The original solution was to have a class level instance variable that holds the index path we want to delete. We would set the index path to delete in our commitEditingStyle method, and then retrieve it in alertView:didDismissWithButtonIndex.

 

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
    NSIndexPath *_indexPathToDelete;
}

...

- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    	NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        _indexPathToDelete = indexPath;
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [_objects removeObjectAtIndex:_indexPathToDelete.row];
        [_tableView deleteRowsAtIndexPaths:@[_indexPathToDelete] withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

This solution works, but why would we want to use this instance variable that is visible to the entire class? Only two methods have interest in this index path, and what if some other method messes with indexPathToDelete and we get some unexpected behavior. It would be better if we could confine this object to only the methods that care about it.

Acceptable Solution

Using the objective-c runtime methods we can associate the index path to the alert view. We will set the association in commitEditingStyle, and retrieve the index path in didDismissWithButtonIndex:.

 

#import <objc/runtime.h>

static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        objc_setAssociatedObject(deleteConfirmation, &deleteKey, indexPath, OBJC_ASSOCIATION_RETAIN);
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = objc_getAssociatedObject(alertView, &deleteKey);
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                               withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

As you can see, we no longer need the instance variable, but we use a new static char variable as the association key. The alert view holds a strong reference to the index path, so it persists from one method to the next as long as the alert view is still in memory. When the alert view is destroyed it will also destroy the index path associated with it. This makes the code clearer and confined to just the methods it is used in instead of having an instance variable that is available to the whole class. We can make this code even better though.

Better Solution

Associated Objects Category

You can create a category on NSObject that simplifies the objective-c runtime calls into a nice API you can use in your normal classes. You could expand on this, but a basic category would be as follows:

NSObject+AssociatedObjects.h

@interface NSObject (AssociatedObjects)
- (void)associateValue:(id)value withKey:(void *)key;
- (id)associatedValueForKey:(void *)key;
@end

 

NSObject+AssociatedObjects.m

#import "NSObject+AssociatedObjects.h"
#import <objc/runtime.h>

@implementation NSObject (AssociatedObjects)

- (void)associateValue:(id)value withKey:(void *)key
{
    objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN);
}

- (id)associatedValueForKey:(void *)key
{
    return objc_getAssociatedObject(self, key);
}

@end

 

Your view controller would then look like this…

 

#import "NSObject+AssociatedObjects.h"
static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        [deleteConfirmation associateValue:indexPath withKey:&deleteKey];
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = [alertView associatedValueForKey:&deleteKey];
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                    withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

I like this a little better because it abstracts out the runtime methods and gives you a nice interface you can use on any object. This accomplishes the same thing, but to me it is much more readable and feels better.

Awesome Solution

According to Apple docs:
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

Also according to Apple docs:
Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.

The only way to add a traditional property-backed by a new instance variable-to an existing class is to use a class extension, as described in ‘Class Extensions Extend the Internal Implementation.'”

With our newfound power, we will add a new property to UIAlertView without subclassing it. As you see in the documentation, it is perfectly valid to declare a property in the category interface, you just can’t create a new instance variable. We don’t need a new instance variable, we will just override the getter and setter of our property to store and retrieve the property by associating it to the alert view.

Let’s create a category on UIAlertView called DeleteConfirmation.

In UIAlertView+DeleteConfirmation.h

@interface UIAlertView (DeleteConfirmation)
@property (nonatomic) NSIndexPath *indexPathToDelete;
@end

 

Now in UIAlertView+DeleteConfirmation.m

#import "UIAlertView+DeleteConfirmation.h"
#import "NSObject+AssociatedObjects.h"

@implementation UIAlertView (DeleteConfirmation)

- (void)setIndexPathToDelete:(NSIndexPath *)indexPathToDelete
{
    [self associateValue:indexPathToDelete withKey:@selector(indexPathToDelete)];
}

- (NSIndexPath *)indexPathToDelete
{
    return [self associatedValueForKey:@selector(indexPathToDelete)];
}

@end

 

Thanks to Erica Sadun, who then credits Gwynne Raskind, for this bad-assery of using the property selector as the association key. According to them, this is valid because Apple’s selector implementation uses a fixed address.

Using the same example, after importing the new category, our view controller code becomes:

 

#import "UIAlertView+DeleteConfirmation.h"

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView
 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        deleteConfirmation.indexPathToDelete = indexPath;
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = alertView.indexPathToDelete;
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                            withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

Beautiful. I love it. The index path to delete looks like any other property you would access.

Conclusion

Ok… maybe this is overkill for the example I gave, but I’m sure you will find other uses for it now that you know about it. It is a great weapon to have at your disposal, and it really helps you write much cleaner, self documenting code.

Source Reference : Press Here

iDev: How to extend existing method in Objective-C

Hi Friends,

Todays you learn a very good technique, I hope:)

With blocks it’s more easy if you need extend your method. But if you will need extend some method of another class, not yours, and you will not be able to get the sources then this solution for you. (And if you will not be able or does not have any reason for creating a subclass)

1. You need create a category of class

2. import runtime in implementation file (.m)

#import <objc/runtime.h>

3. implement your method inside category, for example :

– (void) extend_method {

// your code

//  here will be performed the original method
[self extend_method];

// your code
}

It looks like this method has recursive calls itself, but it’s not true. Look next step

4. add method for replace (you can use +initialize or +load)

+ (void) initialize {
Method original = class_getInstanceMethod(self, @selector(method));
Method replacement = class_getInstanceMethod(self, @selector(extend_method));
method_exchangeImplementations(original, replacement);
}

Done!

Reference : Press Here

Keep Coding 🙂

 

iDev: Secure site trust (Https:) in iOS using NSURLConnection

Secure Coding iPhone and iPad Apps Against MiTM

Many iOS applications use HTTP to connect to server side resources. To protect user-data from being eavesdropped, iOS applications often use SSL to encrypt their HTTP connections.

In this article, I will present sample Objective-C code to illustrate how HTTP(S) connections are established and how to locate insecure code that can leave the iOS application vulnerable to Man in the Middle attacks. I will also discuss how to configure an iOS device to allow for interception of traffic through an HTTP proxy for testing purposes.

A Simple App Using NSURLConnection

The easiest way to initiate HTTP requests in iOS is to utilize the NSURLConnection class. Here is sample code from a very simple application that takes in a URL from an edit-box, makes a GET request, and displays the HTML obtained.

[Please note that the code in this particular example is mostly from Apple’s wonderful tutorial on how to use NSURLConnection]

//This IBAction fires when the user types in a URL and presses GO
– (IBAction) urlBarReturn:(id)sender
{   
    //htmlOutput is the UITextView that displays the HTML
    htmlOutput.text=@””;

    //urlBar is the UITextField that contains the URL to load
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlBar.text]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:60.0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if(!theConnection)
        htmlOutput.text=@”failed”;   
}

– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    //receivedData is of type NSMutableData
    [receivedData setLength:0];

}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];

    NSString *tempString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    htmlOutput.text = [NSString stringWithFormat:@”%@%@”,htmlOutput.text,tempString];

    [tempString release];
}

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    [connection release];

    [receivedData release];

    NSLog(@”Connection failed! Error: %@ %@”,
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

    htmlOutput.text=[NSString stringWithFormat:@”Connection failed! Error %@ %@”,[error localizedDescription],
                     [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@”Succeeded! Received %d bytes of data”,[receivedData length]);

    [connection release];

    [receivedData release];

}

The result is a simple iOS application that fetches HTML code from a given URL.

IOS-app-simple-html
Figure: Simple iOS App using NSURLConnection to fetch HTML from a given URL.

In the screen-shot above, notice that the target URL is https. NSURLConnection seamlessly establishes an SSL connection and fetches the data. If you are reviewing source code of an iOS application for your organization to locate security issues, it makes sense to analyze code that uses NSURLConnection. Make sure you understand how the connections are being inititated, how user input is utilized to construct the connection requests, and if SSL is being used or not. While you are at it, you may also want to watch for NSURL* in general to include invocations to objects of type NSHTTPCookie, NSHTTPCookieStorage, NSHTTPURLResponse, NSURLCredential, NSURLDownload, etc.

Man in the Middle 

74.125.224.49 is one of the IP addresses bound to the host name http://www.google.com. If you browse to https://74.125.224.49, your browser should show you a warning due to the fact that the Common Name field in the SSL certificate presented by the server (www.google.com) does not match the host+domain component of the URL.

IOS-safari-warning Figure: Safari on iOS warning the user due to mis-match of the Common Name field in the certificate.

As presented in the screen-shot above, Safari on iOS does the right thing by warning the user in this situation. Common Name mis-matches and certificates that are not signed by a recognized certificate authority can be signs of a Man in the Middle attempt by a malicious party that is on the same network segment as that of the user or within the network route to the destination.

Ios-NSURL-warning Figure: NSURLConnection’s connection:didFailWithError: delegate is invoked to throw a similar warning.

The screenshot above shows what happens if we attempt to browse to https://74.125.224.49 using our sample App discussed ealier: the connection:didFailWithError: delegate is called indicating an error, which in this case warns the user of the risk and terminates.

This is fantastic. Kudos to Apple for thinking through the security implications and presenting a useful warning message to the user (via NSError).

Unfortunately, it is quite common for application developers to over-ride this protection for various reasons: for example, if the test environment does not have a valid certificate and the code makes it to production. The code below is enough to over-ride this protection outright:

 

– (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

{
                [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

The details on this code is available from this stackoverflow post. There is also a private method for NSURLRequest called setAllowsAnyHTTPSCertificate:forHost: that can be used to over-ride the SSL warnings but Apps that use it are unlikely to get through the App store approval process (Apple prohibits invocations of private API).

If you are responsible for reviewing your organization’s iOS code for security vulnerabilities, I highly recommend you watch for such dangerous design decisions that can put your client’s data and your company’s data at risk.

Intercepting HTTPS traffic using an HTTP Proxy.

As part of performing security testing of applications, it is often useful to intercept HTTP traffic being invoked by the application. Applications that use NSURLConnection‘s implementation as-is will reject your local proxy’s self-signed certificate and terminate the connection. You can get around this easily by implanting the HTTP proxy’s self-signed certificate as a trusted certificate on your iOS device [Note: This is not a loop-hole against the precautions mentioned above: in this case we have access to the physical device and are legitimately implatining the self-signed certificate].

If you are using the Burp Proxy or the Charles Proxy, all you need to do is place the self-signed cert on a HTTP location and browse to it. Instructions for the Burp Proxy are available here, and instructions for Charles Proxy are also available.

Once you have your iOS device or simulator setup using the self-signed certificate of your HTTP proxy, you should be able to intercept HTTPS connections that would otherwise terminate. This is useful for fuzzing, analyzing, and testing iOS applications for security issues.

Source Reference : Click Here..

Thanks 🙂

Keep Coding and innovation new thing in your code … 😉