iDev: UIImage and UIImage View

When we use images in our application then we face different type of scenarios while handling the image. Before we go into the scenarios / situations of image handling in Application, let us understand the concept of UIImage and UIImageView.

Concept of UIImage and UIImageView (container)

UIImage – Bitmap with different formats Ex png and jpeg. Recommended format is png.UIImageView – This is an iOS Widget that acts like a container for holding the image. To hold the image, UIImageView is required.

When UIImage is shown in UIImageView, there is a property (Content Mode) of UIImageView, that render the Image in UIImageView. We mostly use three types of Content Mode property. These are:

  • Scale To Fill
  • Aspect Fit
  • Aspect Fill

How these Content Mode render the image we can see by following examples

  • UIImage of size (100×150)
  • UIImageView of size (200×200)

Different Content modes for placing Image in ImageView

1. Scale To Fill

In this case, content is scaled to fill in ImageView with distorted or same aspect ratio. If the image aspect ratio is different than that of container then final image ratio when fitted in the container will be different and hence the image is finally distorted.

(Aspect Ratio is Width / Height)

InnovationM Image Handling in iOS

2. Aspect Fit

In this case, content is scaled to fit in ImageView (container) without changing the aspect ratio of image . Remainder is transparent.

InnovationM Image Handling in iOS

3. Aspect Fill Without Clipping

In this case, image is scaled to fill in ImageView. Aspect ratio of image is not changed.

InnovationM Image Handling in iOS

4. Aspect Fill With Clipping

In this case, content is scaled to fill in ImageView the same way it happen in the above case but then finally image is cropped to the exact size of the ImageView size.

InnovationM Image Handling in iOS

Calculating new width and height with maintaining aspect ratio

Image original width = 100 and height = 150
Container width  = 200 and height = 200

x-ratio = Container width / Image original width = 200/100 = 2.0
y-ratio =  Container height / Image original height = 200/ 150 =  1.33

Selected ratio = min (x-ratio, y-ratio) = 1.33

Final Image width = Image original width * Selected Ratio = 100 * 1.33 = 133
Final Image height = Image original height * Selected Ratio = 150 * 1.33 = 200

Final Image width x height = 133 x 200 (Original width x height of image was 100 x 150)

Showing Images coming from Server (Different Scenarios)

We can use Aspect Fit mode for all the scenarios. It will serve in every scenario if you don’t want to distort image.

Scenario 1
Image width is lesser than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 200 and height = 200

Final Image width = 133  and height = 200 (Refer the calculations above)
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

Scenario 2 
Image width is greater than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 80 and height = 200

Final Image width = 80 and height = 122
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 3
Image width is lesser than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 200 and height = 120

Final width = 80  and height = 120
Image is scaled down to fit the container.
InnovationM Image Handling in iOS

Scenario 4
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 100

Final width = 66  and height = 100
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 5 (Same Aspect Ratio of Image and ImageView)
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 120

Final width = 80 and height = 120
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 6 (Same Aspect Ratio of Image and ImageView)
Image width is lesser than Container width.
Image height is lesser than Container height.

Image width = 100 and height = 150
UIImageView width = 120 and height = 180

Final width = 120 and height = 180
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

How we change the image size and compress image file size-

Uploading Images to the Server (Different Scenarios)

Many times we have to upload images in an application from device (iPhone, iPad) to the server. It could be a photo clicked from the camera or there was an old image that we choose and upload from the application.

Before uploading we can do two things with the image:

1. Change the width and height of original image.
2. Compress the image to be of smaller file size.

Let us understand them.

1. Change the width and height of original image.

To resize the image, we have to configure the drawing environment for rendering into a bitmap.

1# UIGraphicsBeginImageContextWithOptions()  method is used to create the bitmap-based graphics context.

This method takes two parameters:

  1. Size of image (changed size) and
  2. Scale factor of device as parameter.

Scale factor for Normal Display = 1.0
Scale factor for Retina Display = 2.0

2# – (void) drawInRect:(CGRect)rect; method is used to draw the image in target rectangle.

3# UIGraphicsGetImageFromCurrentImageContext()  method is used to get the resized image from drawing environment.

4# UIGraphicsEndImageContext() method is used to clean up the bitmap drawing environment and remove the graphics context from the top of the context stack.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After resizing image to size (1024,768):
Resized source Image  Size = (1024,768)
Resized source image file size = 2.0 MB

Code Example:

2. Compress the image to be of smaller file size.

We can compress the image file size by following method.

UIImageJPEGRepresentation() This method takes two parameter

  1. UIImage object.
  2. Compress ratio (It can be between 0.0 and 1.0)

This method will return NSData representation of image after compressing.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After compressing image file  size by 0.5:
Resized source Image  Size = (2448, 3264)
Resized source image file size = 534 KB

Code Example:

Depending upon your requirement whether to reduce the size (width and height in pixels) OR reduce the file size OR Both, you may apply the above.

Original Source: Click Here

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: 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