Search This Blog

Sunday, August 23, 2015

How to careate a view programmatically in IOS?

UIWindow* window = [UIApplication sharedApplication].keyWindow;

UIView *polygonView = [[UIView alloc] initWithFrame: CGRectMake ( 0, 0, 200, 150)];
//add code to customize, 
polygonView.backgroundColor = [UIColor blackColor];

[window addSubview:polygonView];
[polygonView release];
 
This is a pattern you will use for not only this but subviews afterwards. Also, another note is with many of the templates, the viewController is already set up with it's own view. When you want to make a custom view, you create it like above but instead of the method above you set the viewControllers view to the newly created view like so:
 
viewController.view = polygonView;
 
======================================================================== 
 
UIView *newView = [[UIView alloc] initWithFrame:mainView.bounds];
[mainView addSubview:newView];
[newView release]; 

Size classes [How to programmatically implement 2 different layouts using size classes]

Scenario: I have a 6 buttons layout. In portrait they should be shown one above the other. In landscape they should be in 2 columns each with 3 buttons.

Use: You can examine the view's trait collection to determine its horizontal and vertical size class.

if ([self.view respondsToSelector:@selector(traitCollection)]){

    if (self.view.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
    ...
    }

}
 
Implement the traitCollectionDidChange: method to automatically be called when a trait changes due to autorotation.

For more information, see UITraitCollection Class Reference and UITraitEnvironment Protocol Reference.

References:
  1. http://stackoverflow.com/questions/25685829/programmatically-implementing-two-different-layouts-using-size-classes
 

Auto Layout [Programmatically]

Auto Layout is a system that lets you lay out your app’s user interface by creating a mathematical description of the relationships between the elements. You define these relationships in terms of constraints either on individual elements, or between sets of elements. Using Auto Layout, you can create a dynamic and versatile interface that responds appropriately to changes in screen size, device orientation, and localization.

How does it work?
Constraints: mathematically defines the relation between 2 views

NSObject > NSLayoutConstraint
+ constraintsWithVisualFormat:options:metrics:views:
+ constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:

Auto Layout is a new way to define dynamic GUIs. Before, we had autoresizing masks, that described how a subview will resize or move when its superview is resized. With Auto Layout you can do the same and also a lot more complicated GUIs quite easily.

Visual Format Language


 



Programmatically auto layout example:


// defined properties inside .h file

// local variables
@property (strong, nonatomic) IBOutlet UILabel *firstName;
@property (strong, nonatomic) IBOutlet UILabel *lastName;
@property (strong, nonatomic) IBOutlet UITextView *textView;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;

// implementation of .m file

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    [self addConstraints];
}

- (void) addConstraints {
    
    [self.view removeConstraints:self.view.constraints];
    
    
    UILabel *firstName = self.firstName;
    UILabel *lastName = self.lastName;
    UIImageView *imageView = self.imageView;
    UITextView *comment = self.textView;
    
    NSDictionary *views = NSDictionaryOfVariableBindings(firstName,lastName,imageView,comment);
    
    NSDictionary *metrics = @{@"width": @160.0, @"horizontalSpacing":@15.0, @"verticalSpacing":@10};
    
    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:
                            @"H:|-[imageView(100)]-horizontalSpacing-[firstName(>=width)]-|"
                                                                   options:NSLayoutFormatAlignAllTop
                                                                   metrics:metrics
                                                                     views:views];
    
    constraints = [constraints arrayByAddingObjectsFromArray:
                   [NSLayoutConstraint constraintsWithVisualFormat:
                    @"H:[imageView]-horizontalSpacing-[lastName(>=width)]-|"
                                                           options:0
                                                           metrics:metrics
                                                             views:views]];

    constraints = [constraints arrayByAddingObjectsFromArray:
                   [NSLayoutConstraint constraintsWithVisualFormat:
                    @"H:[imageView]-horizontalSpacing-[comment(>=width)]-|"
                                                           options:NSLayoutFormatAlignAllBottom
                                                           metrics:metrics
                                                             views:views]];
// if you need to redefine the view, don't mention the Width Constraint again. 
// if you do, it will overlap. that's why, no Width Constraint is assigned in [imageView]

    constraints = [constraints arrayByAddingObjectsFromArray:
                   [NSLayoutConstraint constraintsWithVisualFormat:
                    @"V:|-50-[firstName]-verticalSpacing-[lastName]-verticalSpacing-[comment]"
                                                           options:0
                                                           metrics:metrics
                                                             views:views]];


    [self.view addConstraints:constraints];
    
}



Reference:
  1. Visual format language 
  2. Auto Layout Guide

Thursday, August 20, 2015

How to access app info.plist variables in code

Info.plist  [information property list file]:  is a structured text file that contains essential configuration information for a bundled executable

Attributes from the info.plist for your project are directly accessible by the following...

[[NSBundle mainBundle] objectForInfoDictionaryKey:key_name];


Example:  NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];


An information property list file is a structured text file that contains essential configuration information for a bundled executable. The file itself is typically encoded using the Unicode UTF-8 encoding and the contents are structured using XML. The root XML node is a dictionary, whose contents are a set of keys and values describing different aspects of the bundle. The system uses these keys and values to obtain information about your app and how it is configured. As a result, all bundled executables (plug-ins, frameworks, and apps) are expected to have an information property list file.

By convention, the name of an information property list file is Info.plist. This name of this file is case sensitive and must have an initial capital letter I. In iOS apps, this file resides in the top-level of the bundle directory. In OS X bundles, this file resides in the bundle’s Contents directory. Xcode typically creates this file for you automatically when you create a project of an appropriate type.

Difference between “Use auto layout” and “Use size class” in xcode 6.1?

They are two entirely different things.

Auto Layout:

"Use Auto Layout" determines whether a storyboard uses the Auto Layout features introduced in iOS 6 to automatically layout your interface using constraints.

“Auto Layout is a system that lets you lay out your app’s user interface by creating a mathematical description of the relationships between the elements. You define these relationships in terms of constraints either on individual elements, or between sets of elements.”

Size class:

Size classes require Auto Layout. If the checkbox Use Auto Layout isn’t selected when you select Use Size Classes, Xcode prompts you to enable Auto Layout.

"Use Size Classes" enables a new Xcode 6 feature called size classes that lets you use Auto Layout to build one interface for all devices and customize constraint constants, and certain views and constraints for different interface idioms while reusing the general layout. It saves the work and repetitiveness of having to build and maintain both MainiPhone and MainiPad storyboards.
 
Size Classes let you set different constraints for certain screen sizes. This let’s you go beyond basic stretching layouts.In Xcode 6 Apple introduced Size Classes.


Size classes. Size classes for iOS 8 enable designing a single universal storyboard with customized layouts for both iPhone and iPad. With size classes you can define common views and constraints once, and then add variations for each supported form factor. iOS Simulator and asset catalogs fully support size classes as well.



 Built a new project from scratch in Swift in Xcode 6 (Beta 1) and see File Inspector of Storyboard. There is Use Size Classes below Use Auto Layout. This is the screenshot of this.




Use size classes to enable a storyboard or xib file: to work with all available screen sizes. This enables the user interface of your app to work on any iOS device.
With size classes, a storyboard or xib file can be used for any available screen area. You build your interface as it will look in most sizes, then update only the parts that need to change when the available screen size changes.
A size class identifies a relative amount of display space for the height and for the width. Each dimension can be either compact, for example, the height of an iPhone in landscape orientation, or regular, for example, the height or width of an iPad. Because much of the layout of an app does not need to change for any available screen size, there is an additional value, any.
The available screen size for a view controller is based on 3 factors:
  • The screen size of the device.
  • The orientation of the device.
  • The portion of the screen available to the view controller. For example, when a split view controller displays both the master and detail controllers, neither controller has access to the full screen.
To create a view controller that uses size classes, begin by laying out your design abstractly—a height and width size class of any. To design for more specific available areas, choose appropriate size classes. As needed, add or remove views, change the font used to display text, and add, remove, or edit constraints. In this way, you can more easily deploy your app to different devices in various orientations.
You can change four aspects of presentation in a size class. For constraints, you can change the constant for a constraint and you can change whether the constraint is installed in the view hierarchy. For views, you can change whether a view is installed in the view hierarchy and you can change the font used to display text.
These four changes enable you to adapt your interface for a size class by:
  • Changing the size or position of views
  • Adding or removing views
  • Adding or removing constraints
  • Changing the font in labels, fields, text views, and buttons
As you design your app, preview how its layout appears on specific devices from within Xcode.

Create a text field, button programmatically

    UITextField *userNameField = [[UITextField alloc] initWithFrame:CGRectMake(20, 30, 300, 40)];
    userNameField.placeholder = @"userName";
    userNameField.accessibilityLabel = @"UserName Field";
    userNameField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userNameField];
   
   
    UITextField *passwordField = [[UITextField alloc] initWithFrame:CGRectMake(20, 90, 300, 40)];
    passwordField.placeholder = @"password";
    passwordField.secureTextEntry = YES;
    passwordField.accessibilityLabel = @"Password Field";
    passwordField.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:passwordField];
   
   
    UIButton * submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    submitButton.frame = CGRectMake(20, 150, 150, 40);
    [submitButton setTitle:@"Submit" forState:UIControlStateNormal];
    submitButton.accessibilityLabel = @"Submit Button";
    [submitButton addTarget:self action:@selector(submitButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    submitButton.backgroundColor = [UIColor redColor];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:submitButton];

Implementation example of button click:

-(void)submitButtonPressed:(id)Sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)loginButtonPressed:(id)sender{
    LoginViewController *loginViewController = [LoginViewController new];   // create a modal
    [self presentViewController:loginViewController animated:YES completion:nil];  // preent it as a model
}

Tell some of the KIF methods to test

waitForTappableViewWithAccessibilityLabel
waitForViewWithAccessibilityLabel

tapViewWithAccessibilityLabel

enterText:  intoViewWithAccessibilityLabel:

Examples:

    [tester waitForTappableViewWithAccessibilityLabel:@"Login Button"];
    [tester tapViewWithAccessibilityLabel:@"Login Button"];
    [tester waitForViewWithAccessibilityLabel:@"UserName Field"];
    [tester enterText:@"myUserName" intoViewWithAccessibilityLabel:@"UserName Field"];
    [tester enterText:@"myPassword" intoViewWithAccessibilityLabel:@"Password Field"];
    [tester tapViewWithAccessibilityLabel:@"Submit Button"];
   
    // Back to main view
    [tester waitForViewWithAccessibilityLabel:@"Login Button"];


ViewController life cycle

at first it loads viewDidLoad

- (void)viewWillAppear:(BOOL)animated;  
// Called when the view is about to made visible. Default does nothing
- (void)viewDidAppear:(BOOL)animated;   
// Called when the view has been fully transitioned onto the screen. Default does nothing
- (void)viewWillDisappear:(BOOL)animated;
// Called when the view is dismissed, covered or otherwise hidden. Default does nothing
- (void)viewDidDisappear:(BOOL)animated;
// Called after the view was dismissed, covered or otherwise hidden. Default does nothing






if you implement by the line NSLog(@"see what is that %s ", __func__); you will see the first 3 is coming one by one.

What is the difference between NIB and XIB Interface Builder file formats?

  • xib = xml interface builder, nib = next interface builder
  • When you compile your project, .xib file will get compiled into nib.  
  • Functionally nothing but the xib is a source control friendly format
  • A Xib is more or less an XML document, it is the uncompiled read/write version of a nib. Once you compile a xib it becomes a nib.
  • XIB is actually XML file. NIB is binary.
  • XIB: Text-based XML. NIB: Archives, created by Xcode.

As of Interface Builder version 3, a new file format (with extension .xib) has been added, which is functionally identical to .nib, except it is stored in a flat file, making it more suitable for storage in revision control systems and processing by tools such as diff.

XIBs are flat files rather than being a bundle. This makes it easier for SCM systems to deal with. When you compile your app, the XIB is compiled into a NIB file for inclusion in your app.
The compiled NIB that is included in the app bundle is no longer editable in Interface Builder and is much smaller than the equivalent XIB or legacy NIB file.

From wikipedia:

Interface Builder is a software development application for Apple's Mac OS X operating system. It is part of Xcode (formerly Project Builder), the Apple Developer Connection developer's toolset. Interface Builder allows Cocoa and Carbon developers to create interfaces for applications using a graphical user interface. The resulting interface is stored as a .nib file, short for NeXT Interface Builder, or more recently, as a .xib file.

Interface Builder is descended from the NeXTSTEP development software of the same name. A version of Interface Builder is also used in the development of OpenStep software, and a very similar tool called Gorm exists for GNUstep. On March 27, 2008, a specialized iPhone version of Interface Builder allowing interface construction for iPhone applications was released with the iPhone SDK Beta 2.

Interface Builder was intentionally developed as a separate application, to allow interaction designers to design interfaces without having to use a code-oriented IDE, but as of Xcode 4, Apple has integrated its functionality directly into Xcode.

Interface Builder saves an application's interface as a bundle that contains the interface objects and relationships used in the application. These objects are archived (a process also known as serialization or marshalling in other contexts) into either an XML file or a NeXT-style property list file with a .nib extension. Upon running an application, the proper NIB objects are unarchived, connected into the binary of their owning application, and awakened. Unlike almost all other GUI designer systems which generate code to construct the UI (notable exceptions being Glade, Embarcadero Technologies's Delphi and C++ Builder, which stream UI objects similarly), NIBs are often referred to as freeze dried because they contain the archived objects themselves, ready to run. As of Interface Builder version 3, a new file format (with extension .xib) has been added, which is functionally identical to .nib, except it is stored in a flat file, making it more suitable for storage in revision control systems and processing by tools such as diff.

Ref: https://en.wikipedia.org/wiki/Interface_Builder#Design

More discussion: [Ref: http://www.speirs.org/blog/2007/12/5/what-are-xib-files.html]
The Xcode tools in Leopard introduced a new file format for user interfaces. In the brach of the prehistory of Mac OS X that includes NeXT, interfaces were defined in files known as NIBs, from their .nib extension.

A NIB file is a Mac OS X package containing, usually, a keyedobjects.nib file and a classes.nib file. When building an application, these files are copied into the app's bundle and are loaded at runtime to provide the user interface for the application. For what comes next, bear in mind that the NIB in your Xcode project is the same NIB that is loaded at runtime in the application.

Interface Builder 3 on Leopard introduces a new file format: XIB. The developer experience of editing XIB files in Interface Builder is identical to editing a NIB file but, in many other ways a XIB is radically different from a NIB file. If I had one criticism of WWDC '07, it was that they didn't spend enough time explaining XIBs and their implications.

File Format

Firstly, the XIB file format is completely different from that of a NIB. A XIB is not a package - it is a single self-contained XML file. The XML schema is specific to XIBs - it is not a simple XML Property List.

This brings a couple of advantages. Firstly, it's a benefit for users of tools that are not package-aware. In early days, Interface Builder would blow away the .svn directory inside the NIB package. That hasn't been a problem for years, but other tools may still have issues.

Secondly, the file format is vaguely human-understandable. It is very dense and not entirely obvious, but one can make some sense of it. This helps in some of those last-ditch situations where you're grepping the file to find out where a particular binding is referenced.

It is worth pointing out two things that this text-based file format does not immediately deliver: hand-editability and mergability. The XIB file is an XML representation of an object graph and, as such, it is considered dangerous to edit it by hand. Merging is just a machine-assisted form of hand editing and is likely problematic. However, the text format might assist in understanding where the conflicts lie.

Working with XIBs

The primary tool for editing XIB files is, of course, Interface Builder. For many years, there has been a command line tool for manipulating nibs called nibtool. In Leopard, nibtool has been renamed (or replaced - I'm not sure) by ibtool and has acquired many new tricks.

The man page for ibtool contains a lot of detail, but it's worth noting a couple of new capabilities: the --convert option will rename old classes to new. Presumably it is ibtool --convert that allows Xcode 3.0's refactoring tools to reach into interface files.

There are also many options in ibtool for printing the details of a NIB or XIB to an XML Property List, including --objects, --connections, --hierarchy and --classes, although a mode to conveniently list the bindings in an interface sadly isn't available.

Deploying XIBs

The crucial difference between XIB and NIB for deployment is that a XIB is not a deployable file. Xcode 3 will compile a XIB into a deployable NIB when the project is built and will include that deployable NIB in the finished application.

If you're using XIB in your Xcode projects, you might see a CompileXIB build operation going past. What's actually happening there is that Xcode is calling:

ibtool --errors --warnings --notices --output-format human-readable-text --compile your.xib output.nib

It's ibtool that compiles XIB to NIB, not Xcode itself, and it emits useful warnings and errors about your XIB files right in the Xcode build window. I've found this to be very, very valuable when working with my XIB-based projects.

The NIB file produced by compiling a XIB file in ibtool is a deployment-only file. Unlike most earlier NIB files, one cannot extract a deployment NIB file from an application and open it in Interface Builder for inspection. This is slightly sad, since it makes it harder to learn how others did things. However, in recent years, it has rarely been a worthwhile learning experience to open deployed NIBs, since all one usually finds is a morass of "Custom View" panels.

XIB Wishlist

Interface Builder 3, XIBs, and the new capabilities of ibtool are a great leap forward in Mac development. I've been using XIB files exclusively in my Leopard-only development. I haven't yet converted FlickrExport to be XIB-based. They work perfectly for me, but I have heard of the occasional problem with opening a XIB-compiled NIB on Tiger, so I'm not sure that I'll adopt XIB files in code that has to be Tiger-compatible.

The one remaining thing I really want to see in this tool set is the ability to diff and ultimately merge XIB files, but I would be very happy to just get diff capabilities right now. It doesn't even need to be graphical - just a text report would be great. It seems that the XIB file format lays the foundation for something like that to happen in the future. Let's hope we get there.

Further Reading

There's not a huge amount about XIBs in there, but the Interface Builder 3.0 Release Notes are worth reading.

[Update: Jens Ayton pointed out that I had, incorrectly, used the term 'bundle' in a number of places to refer to NIB files which are, in fact, packages.]


What is the difference between a .xib file and a .storyboard?

Apple introduced the concept of "storyboarding" in iOS5 SDK to simplify and better manage screens in your app. You can still use the .xib way of development.

Pre-storyboard, each UIViewController had an associated .xib with it. Storyboard achieves two things:
  1. .storyboard is essentially one single file for all your screens in the app and it shows the flow of the screens. You can add segues/transitions between screens, this way. So, this minimizes the boilerplate code required to manage multiple screens.
  2. Minimizes the overall no. of files in an app.
You can avoid using Storyboard while creating a new project by leaving the "Use Storyboard" option unchecked.

  • Storyboarding replace the need for .xib files
  • 1 .storyboard file = 'n' no of .xib files 
  • A storyboard is like a canvas where you put all your .xib files. 

You could refer this tutorial to get started.

Storyboard supports > iOS 5

What aret the differences between a deep copy and a shallow copy?

Shallow copy (also know as Address Copy):
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copy:
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.


If B is a shallow copy of A, then it is like B = [A assign];
B and A point to the same memory location
If B is a deep copy of A, then it is like B = [A copy];
B and A point to different memory locations
B memory address is same as A's
B has same contents as A's

 Shallow and deep copies of an object



Copy by default gives a shallow copy

That is because calling copy is the same as copyWithZone:NULL also known as copying with the default zone. The copy call does not result in a deep copy. In most cases it would give you a shallow copy, but in any case it depends on the class. For a thorough discussion I recommend the Collections Programming Topics on the Apple Developer site.

initWithArray:CopyItems: gives a one-level deep copy

NSArray *deepCopyArray = [[NSArray alloc] initWithArray:someArray copyItems:YES];

NSCoding is the Apple recommended way to provide a deep copy

For a true deep copy (Array of Arrays) you will need NSCoding and archive/unarchive the object:
NSArray *trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:oldArray]];

Other way of explanation

 
Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data.

Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy.

Char *A = {‘a’,’b’,’c’};
Char *B = {‘x’,’y’,’z’};
B = A;

Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array.

while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected.

[Ref: https://iphonecodecenter.wordpress.com/2013/08/26/difference-between-shallow-copy-and-deep-copy/ ]



References:

Wednesday, August 19, 2015

Sample code

    func displayKeyboard(){
        self.userInputTextField .becomeFirstResponder()
    }
   
    func disableKeyboard(){
        self.userInputTextField .resignFirstResponder()
    }

=========================  

 func getCurrentCurrencyData() -> Void{
        let currencyURL = NSURL(string: "http://api.fixer.io/latest?base=USD")
       
       
        let sharedSession = NSURLSession.sharedSession()
        let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(currencyURL!, completionHandler: { (location: NSURL!, response:NSURLResponse!, error: NSError!) -> Void in
           
           
            if(error == nil){
                let dataObject = NSData(contentsOfURL: location)
                let currencyDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary
               
               
                let rates = Currency(currencyDictionary: currencyDictionary)
               
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                   
                    var userInputStringValue: String = self.userInputTextField.text
                    var userInputDoubleValue : Double = NSString(string: userInputStringValue).doubleValue
                   
                   
                    if(userInputDoubleValue > 0){
                       
                        var gbpCurrentValue = rates.gbp * userInputDoubleValue
                        var eurCurrentValue = rates.eur * userInputDoubleValue
                        var jpyCurrentValue = rates.jpy * userInputDoubleValue
                        var brlCurrentValue = rates.brl * userInputDoubleValue
                       
                        var resultString = "UK Pounds - (GBP): " + gbpCurrentValue.description + "\n" +
                            "EU Euro - (Euro)     : " + eurCurrentValue.description + "\n" +
                            "Japan Yen - (JPY)   : " + jpyCurrentValue.description + "\n" +
                            "Brazil Reais - (BRL): " + brlCurrentValue.description as NSString
                       
                       
                        self.resultTextView.text = resultString as String
                        self.resultTextView.font = UIFont(name: "ArialMT", size: 15)
                       
                    }
                       
                    else{
                        self.resultTextView.text = "Please enter a valid dollar amount which is greater then 0"
                    }
                   
                   
                })
               
               
            }
               
            else{
               
                let networkIssueController = UIAlertController(title: "Error", message: "Unable to load data. Connectivity error!", preferredStyle: .Alert)
               
                let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
                networkIssueController.addAction(okButton)
               
               
               
                //                let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
                //                networkIssueController.addAction(cancelButton)
               
                self.presentViewController(networkIssueController, animated: true, completion: { () -> Void in
                    //
                })
               
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.resultTextView.text = "Unable to load data due to connectivity error! Please press the CONVERT button again to get the conversion rates!"
                    self.resultTextView.font = UIFont(name: "ArialMT", size: 15)
                    self.resultTextView.textColor = UIColor.redColor()
                })
               
                println(error)
            }
           
        })
        downloadTask.resume()
    }

What are the differences between pixel and points in iPhone?

A pixel on iOS is the full resolution of the device, which means if I have an image that is 100x100 pixels in length, then the phone will render it 100x100 pixels on a standard non-retina device. However, because newer iPhones have a quadrupled pixel density, that same image will render at 100x100 pixels, but look half that size. The iOS engineers solved this a long time ago (way back in OS X with Quartz) when they introduced Core Graphics' point system. A point is a standard length equivalent to 1x1 pixels on a non-retina device, and 2x2 pixels on a retina device. That way, your 100x100 image will render twice the size on a retina device and basically normalize what the user sees.

It also provides a standard system of measurement on iOS devices because no matter how the pixel density chanes, there have always been 320x480 points on an iPhone screen and 768x1024 points on an iPad screen.*

But at the same time, you can basically disregard the documentation considering that retina devices were introduced with iOS 4 at a minimum, and I don't know of too many people still running iOS 3 on a newer iPhone. But if such a case arises, your UIImage would need to be rendered at exactly twice its dimensions in pixels on a retina iPhone to make up for the pixel density difference.

A pixel is a single square 'picture element' (hence pix-el), i.e. a single dot in your image. A 10x10 image is made up of a set of pixels in a grid 10 wide by 10 high, totaling 100 pixels.
The 'point' (pt) on the other hand is a unit of length, commonly used to measure the height of a font, but technically capable of measuring any length. In applications, 1pt is equal to exactly 1/72th of an inch; in traditional print technically 72pt is 0.996264 inches, although I think you'll be forgiven for rounding it up!
How many pixels = 1pt depends on the resolution of your image. If your image is 72ppi (pixels per inch), then one point will equal exactly one pixel.

What are the difference between “copy” and “retain”?

  • Retaining and copying are two different things, the first is conceptually call-by-reference while the second is call-by-value 
  • Retain increases the retain count of an object by 1 and takes ownership of an object.
  • Whereas copy will copy the data present in the memory location and will assign it to the variable so in the case of copy you are first copying the data from a location assign it to the variable which increases the retain count.
  • Just remember that retain works on reference and copy works on value
  • simple difference: whenever you write retain it will increment the count and whenever you write copy it will make reference and does not increment the count for example let say:-
NSObject *ret=[obj1 retain]; It will increment the count by 1 in memory(count will become 2) NSObject *cop=[obj1 copy]; It will not increment the count here count will be 1 only it just create the new reference in memory. (count will remain same 1 only)

In a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
When dealing with NSStrings in particular, you may not be able to assume that whoever is giving you an NSString is truly giving you an NSString. Someone could be handing you a subclass (NSMutableString, in this case) which means that they could potentially modify the values under the covers. If your application depends on the value passed in, and someone changes it on you, you can run into trouble.

  1. assign
    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:
    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:
    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

I'm inferring from the presence of retain, that you're employing MRR (manual retain and release). In MRR, this code results in:
@implementation ABC

-(void) fun1
{
  ObjectA * obj1 = [[ObjectA alloc] init];  // retainCount = +1
  ObjectA * obj2 = obj1;                    // unchanged

  // you have one instance of `ObjectA` with a retain count of +1
  // both `obj1` and `obj2` point to the same single instance
}

-(void) fun2
{
  ObjectA * obj1 = [[ObjectA alloc] init];  // retainCount = +1
  ObjectA * obj2 = [obj1 retain];           // retainCount = +2

  // you have one instance of `ObjectA` with a retain count of +2
  // both `obj1` and `obj2` point to the same single instance
}

-(void) fun3
{
  ObjectA * obj1 = [[ObjectA alloc] init];  // retainCount of `obj1` object = +1
  ObjectA * obj2 = [obj1 copy];             // retainCount of `obj2` object = +1

  // you have two instances of `ObjectA`, each with a retain count of +1
  // `obj1` points to one instance and `obj2` point to the other
}

-(void) fun4
{
  ObjectA * obj1 = [[ObjectA alloc] init];  // retainCount of `obj1` object = +1
  ObjectA * obj2 = [obj1 mutableCopy];      // retainCount of `obj2` object = +1

  // you have two instances of `ObjectA`, each with a retain count of +1
  // `obj1` points to one instance
  // `obj2` points to another instance, which is mutable copy of the `obj1` instance
}

@end

Clearly, in all of these cases, in MRR, if you don't do something with the ObjectA instances by the end of the method, you'll be leaking (because you're abandoning the last known reference to these objects). If using ARC, the necessary clean up is performed.
By the way, in the future, you should examine the results yourself. For example, if you added these diagnostic statements to the end of each method, you'd clearly see what's going on:
NSLog(@"%s: [obj1 (%p) retainCount] = %d", __FUNCTION__, obj1, [obj1 retainCount]);
NSLog(@"%s: [obj2 (%p) retainCount] = %d", __FUNCTION__, obj2, [obj2 retainCount]);
That displays the address of the object to which the variable points, as well as the object's current retainCount. Needless to say, you shouldn't be using retainCount in production code, but it's useful solely for diagnostic purposes.
By way, while it's good that you're trying to understand the memory management, I would suggest that you seriously consider using automatic reference counting (ARC). It makes memory management much easier (no retain, release or retainCount). And if you're determined to stick with manual retain and release (MRR), then make sure you run your code through the static analyzer ("Analyze" on Xcode's "Product" menu), as it's pretty decent in identifying the sort of problems that plague MRR code.

References:

Tuesday, August 18, 2015

Git Summary using Bitbucket and Soruce Tree

Git initialization: 
 
mkdir /path/to/your/project
cd /path/to/your/project
git initgit remote 
add origin https://tintinburi@bitbucket.org/deveoteam/testtestproject.git
 
Create your first file, commit, and push

echo "tintin buri" >> contributors.txtgit 
add contributors.txtgit 
commit -m 'Initial commit with contributors'
git push -u origin master 


Already have a Git repository on your computer? Let's push it up to Bitbucket.
                  
cd /path/to/my/repogit remote 
add origin https://tintinburi@bitbucket.org/deveoteam/testtestproject.gitgit 
push -u origin --all # pushes up the repo and its refs for the first timegit 
push -u origin --tags # pushes up any tags
 
Git installation notes:
https://confluence.atlassian.com/display/BITBUCKET/Set+up+Git 
 
First save your information to git

git config --global user.name "Emma Paris"
git config --global user.email "eparis@atlassian.com" 

 
Tutorials 
https://confluence.atlassian.com/display/BITBUCKET/SourceTree+Tutorial%3A+Request+supplies+for+your+space+station

Bitbucket Tutorials: Teams in Space Training Ground


Learn Git
Learn Mercurial
Learn SourceTree
Equip yourself with pull requests