Tuesday, December 20, 2011

NSMutableArray sorting


Source: http://adeem.me/blog/2009/05/02/tutorial-tips-sorting-filtering-filter-nsmutablearray-and-sorting-nsmutablearray-by-ascending-or-objects-items-or-specified-key-or-key-value-or-by-nsnumber/
1. Sorting NSArray/NSMutableArray:
Sorting NSMutableArray is very simple:


NSMutableArray *arrayToFilter = [[NSMutableArray arrayWithObjects:@"Photoshop", @"Flex", @"AIR",@"Flash", @"Acrobat", @"<span id="IL_AD7" class="IL_AD">After Effects</span>", @"ColdFusion", @"Dreamweaver", nil] autorelease];

NSMutableArray *productsToRemove = [[NSMutableArray array] autorelease];
for (NSString *products in arrayToFilter) {
if (fliterText &amp;amp;amp;&amp;amp;amp; [products rangeOfString:fliterText options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)
[productsToRemove addObject:products];
}
[arrayToFilter removeObjectsInArray:productsToRemove];

2. Creating NSMutableArray based on searched text in Array:


NSMutableArray *arrayToFilter = [NSMutableArray arrayWithObjects:@"Photoshop", @"Flex", @"AIR",@"Flash", @"Acrobat", @"After Effects", @"ColdFusion", @"Dreamweaver", nil];
NSMutableArray *productsToRemove = [NSMutableArray array];
for (NSString *products in arrayToFilter) {
if (fliterText &amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp; [products rangeOfString:fliterText options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)
[productsToRemove addObject:products];
}
[arrayToFilter removeObjectsInArray:productsToRemove];
3. Sorting NSMutableArray (based on key) which contains objects 
First, you’ll need to create an NSSortDescriptor and tell it which key to sort the array on.


NSSortDescriptor *lastNameSorter = [[NSSortDescriptor alloc] initWithKey:@"lastName"ascending:YES];
[personList sortUsingDescriptors:[NSArray arrayWithObject:lastNameSorter]];

Saturday, December 17, 2011

Display the multi-lines in the UILabel

To use NSString method, "sizeWithFont:constrainedToSize: lineBreakMode:"
It figure out the UILabel size to accommodate the long String.




//  init the content of string

NSString *string = @"Cocos2d-x open source project is C++ version of cocos2d-iphone. We focus on making cocos2d framework cross multiple platforms. Mobile games can be written on the top of cocos2d-x in C++ or Lua language, via the COMPLETELY SAME API as cocos2d-iphone, they can easily be built & run on iOS, Android, Samsung Bada and BlackBerry Tablet OS. Cocos2d-x also supports Windows & Linux, therefore we can debug source code easily and write editors on desktop operating systems."; 

// Determine the size of UILabel for the string
CGSize aSize = [string sizeWithFont: [UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(250.0, 999.0) lineBreakMode:UILineBreakModeWordWrap]; 

 // Declare UILabel,
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(20, 20, aSize.width, aSize.height)]; 

 // init the label
label.backgroundColor = [UIColor grayColor]; 
label.textColor = [UIColor redColor]; 
label.font = UIFont systemFontOfSize:18;
label.lineBreakMode = UILineBreakModeWordWrap; 
label.text = string; 
label.numberOfLines = 0;  
[self.view addSubview:label]; 

Tuesday, December 13, 2011

Passing the data between the viewControllers

Source: http://www.devx.com/wireless/Article/42476/1954
For the detail, please visit above website.


Sometimes you need to pass data from one view to another. The easiest way is to create a property on the target view and set (or retrieve) that property from the calling view.
Here's an example. Double-click the VCExampleViewController.xib file and add a DatePicker view to the View window (see Figure 18).
Figure 18. Enhancing the View: Add a DatePicker view to the first View.


In the VCExampleViewController.h file, create an outlet for this DatePicker view and then expose it as a property:

#import <UIKit/UIKit.h>
@interface VCExampleViewController : UIViewController {
    //---outlet for the DatePicker view---
    IBOutlet UIDatePicker *datePicker;
}
//---expose this outlet as a property---
@property (nonatomic, retain) UIDatePicker *datePicker;

-(IBAction) displayView:(id) sender;

@end

In the VCExampleViewController.xib window, control-click and drag the File's Owner Item to the DatePicker view and then select datePicker.
In the SecondViewController.h, create an object of type UIDatePicker and then expose it as a property:

#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController {
    //---object of type UIDatePicker---
    UIDatePicker *selectedDatePicker;
}
//---expose the object as a property---
@property (nonatomic, retain) UIDatePicker *selectedDatePicker;

-(IBAction) btnReturn:(id) sender;

@end

In the SecondViewController.m file, add the following lines (in bold) to the viewDidLoad method:

#import "SecondViewController.h"
@implementation SecondViewController
@synthesize selectedDatePicker;
- (void)viewDidLoad {
    //---display the date and time selected in the previous view---
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"MMM dd, yyyy HH:mm"];
    
    UIAlertView *alert = [[UIAlertView alloc] 
                             initWithTitle:@"Date and time selected" 
                             message:[formatter stringFromDate:selectedDatePicker.date] 
                             delegate:self 
                             cancelButtonTitle:@"OK" 
                             otherButtonTitles:nil];
    [alert show];
    [alert release];    
    [super viewDidLoad];
}
- (void)dealloc {
    //---release the memory used by the property---
    [selectedDatePicker release];
    [super dealloc];
}

Finally, in the VCExampleViewController.m file, add the line shown in bold:

#import "VCExampleViewController.h"
#import "SecondViewController.h"
 
@implementation VCExampleViewController
SecondViewController *secondViewController;
@synthesize datePicker;
-(IBAction) displayView:(id) sender{
secondViewController = [[SecondViewController alloc] 
                                initWithNibName:@"SecondView" 
                                bundle:nil];
    //---set the property of the second view with the DatePicker view in the current view---
    secondViewController.selectedDatePicker = datePicker;

Figure 19. Passing Values Between Views: The second view now displays the date and time selected from the DatePicker in the first view.

     [UIView beginAnimations:@"flipping view" context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:
          UIViewAnimationTransitionCurlDown 
          forView:self.view cache:YES];
    
    [self.view addSubview:secondViewController.view];
    [UIView commitAnimations];    
}

Press Command-r to test the application. Select a date and time in the DatePicker view and press the Display SecondView button. The second view will now display the date and time selected in the first view (see Figure 19).

You've seen how to pass values between two views. As these operations form the basics of iPhone programming, you should be well on your way to creating your own iPhone applications.

Monday, December 12, 2011

File management in iOS

The iPhone provides a comprehensive set of operations for working with files and directories. NSFileManager includes methods for querying the contents of directories, creating, renaming and deleting contents, as well as getting/setting file attributes (readable, writeable, etc).
Point to the Documents Directory
Each application has its own sandbox in which you can read/write files. Files written to the sandbox are persistent across invocations of the application, including across application updates.
You can locate the Documents directory in the sandbox as shown below:
// For error information
NSError *error;
 
// Create file manager
NSFileManager *fileMgr = [NSFileManager defaultManager];
 
// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() 
         stringByAppendingPathComponent:@"Documents"];
Creating a File
With the documents directory available, we can now use that path to create a new file in the sandbox and write a few lines of text:
// File we want to create in the documents directory 
// Result is: /Documents/file1.txt
NSString *filePath = [documentsDirectory 
         stringByAppendingPathComponent:@"file1.txt"];
 
// String to write
NSString *str = @"iPhone Developer Tips\nhttp://iPhoneDevelopTips,com";
 
// Write the file
[str writeToFile:filePath atomically:YES 
         encoding:NSUTF8StringEncoding error:&error];
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@",
         [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
We build a path to the file we want to create (file1.txt), initialize a string to write into the file, and write out the contents. The last line shows a directory listing of what is in the Documents directory after we create the file, see the figure below:
Renaming a File
To rename a file we move the file to a new path. The code below creates the destination path we are after, requests to move the file, and shows the Documents directory after the move.
// Rename the file, by moving the file
NSString *filePath2 = [documentsDirectory 
                                 stringByAppendingPathComponent:@"file2.txt"];
 
// Attempt the move
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
  NSLog(@"Unable to move file: %@", [error localizedDescription]);
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@", 
         [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
After moving the file, the output should look similar to the image below:
Deleting a File
To round out this tip, let’s look at how to delete a file:
// Attempt to delete the file at filePath2
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
  NSLog(@"Unable to delete file: %@", [error localizedDescription]);
 
// Show contents of Documents directory
NSLog(@"Documents directory: %@",
         [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
Once the file is deleted, as expected, the Documents directory is now empty:
These examples touch the surface of working with files. Check out the documentation forNSFileManager for all the specifics.


Source:
http://iphonedevelopertips.com/data-file-management/iphone-file-system-creating-renaming-and-deleting-files.html