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 🙂

 

Advertisements

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