月度归档:2014年01月

7Performing UI-Related Tasks with GCD–Block-Asyn

typedef struct{
    char *title;
    char *message;
    char *cancelButtonTitle;
} AlertViewData;

void displayAlertView(void *paramContext){
    
    AlertViewData *alertData = (AlertViewData *)paramContext;
    
    NSString *title =
    [NSString stringWithUTF8String:alertData->title];
    
    NSString *message =
    [NSString stringWithUTF8String:alertData->message];
    
    NSString *cancelButtonTitle =
    [NSString stringWithUTF8String:alertData->cancelButtonTitle];
    
    [[[UIAlertView alloc] initWithTitle:title
                                message:message
                               delegate:nil
                      cancelButtonTitle:cancelButtonTitle
                      otherButtonTitles:nil, nil] show];
    
    free(alertData);
    
}

//- (BOOL)            application:(UIApplication *)application
//  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//    
//    dispatch_queue_t mainQueue = dispatch_get_main_queue();
//    
//    AlertViewData *context = (AlertViewData *)
//    malloc(sizeof(AlertViewData));
//    
//    if (context != NULL){
//        context->title = "GCD";
//        context->message = "GCD is amazing.";
//        context->cancelButtonTitle = "OK";
//        
//        dispatch_async_f(mainQueue,
//                         (void *)context,
//                         displayAlertView);
//    }
//    
//    self.window = [[UIWindow alloc] initWithFrame:
//                   [[UIScreen mainScreen] bounds]];
//    
//    self.window.backgroundColor = [UIColor whiteColor];
//    [self.window makeKeyAndVisible];
//    return YES;
//}

//- (BOOL)            application:(UIApplication *)application
//  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//    
//    dispatch_queue_t mainQueue = dispatch_get_main_queue();
//    
//    dispatch_async(mainQueue, ^(void) {
//        
//        [[[UIAlertView alloc] initWithTitle:@"GCD"
//                                    message:@"GCD is amazing!"
//                                   delegate:nil
//                          cancelButtonTitle:@"OK"
//                          otherButtonTitles:nil, nil] show];
//        
//    });
//    
//    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//    // Override point for customization after application launch.
//    self.window.backgroundColor = [UIColor whiteColor];
//    [self.window makeKeyAndVisible];
//    return YES;
//}

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
    dispatch_async(mainQueue, ^(void) {
        NSLog(@"Current thread = %@", [NSThread currentThread]);
        NSLog(@"Main thread = %@", [NSThread mainThread]);
    });
    
    self.window = [[UIWindow alloc] initWithFrame:
                   [[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    
    return YES;
}

Performing Non-UI-Related Tasks Synchronously with GCD

void printFrom1To1000(void *paramContext){
    
    NSUInteger counter = 0;
    for (counter = 1;
         counter <= 1000;
         counter++){
        
        NSLog(@"Counter = %lu - Thread = %@",
              (unsigned long)counter,
              [NSThread currentThread]);
        
    }
    
}

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_sync_f(concurrentQueue,
                    NULL,
                    printFrom1To1000);
    
    dispatch_sync_f(concurrentQueue,
                    NULL,
                    printFrom1To1000);
    
    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Performing Non-UI Related Tasks Asynchronously with GCD

- (NSString *) fileLocation{
    
    /* Get the document folder(s) */
    NSArray *folders =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                        NSUserDomainMask,
                                        YES);
    
    /* Did we find anything? */
    if ([folders count] == 0){
        return nil;
    }
    
    /* Get the first folder */
    NSString *documentsFolder = folders[0];
    
    /* Append the file name to the end of the documents path */
    return [documentsFolder
            stringByAppendingPathComponent:@"list.txt"];
    
}

- (BOOL) hasFileAlreadyBeenCreated{
    
    BOOL result = NO;
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    if ([fileManager fileExistsAtPath:[self fileLocation]]){
        result = YES;
    }
    
    return result;
}

- (void) viewDidAppear:(BOOL)paramAnimated{
    
    [super viewDidAppear:paramAnimated];
    
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    /* If we have not already saved an array of 10,000
     random numbers to the disk before, generate these numbers now
     and then save them to the disk in an array */
    dispatch_async(concurrentQueue, ^{
        
        NSUInteger numberOfValuesRequired = 10000;
        
        if ([self hasFileAlreadyBeenCreated] == NO){
            dispatch_sync(concurrentQueue, ^{
                
                NSMutableArray *arrayOfRandomNumbers =
                [[NSMutableArray alloc]
                 initWithCapacity:numberOfValuesRequired];
                
                NSUInteger counter = 0;
                for (counter = 0;
                     counter < numberOfValuesRequired;
                     counter++){
                    unsigned int randomNumber =
                    arc4random() % ((unsigned int)RAND_MAX + 1);
                    
                    [arrayOfRandomNumbers addObject:
                     [NSNumber numberWithUnsignedInt:randomNumber]];
                }
                
                /* Now let's write the array to disk */
                [arrayOfRandomNumbers writeToFile:[self fileLocation]
                                       atomically:YES];
                
            });
        }
        
        __block NSMutableArray *randomNumbers = nil;
        
        /* Read the numbers from disk and sort them in an
         ascending fashion */
        dispatch_sync(concurrentQueue, ^{
            
            /* If the file has now been created, we have to read it */
            if ([self hasFileAlreadyBeenCreated]){
                randomNumbers = [[NSMutableArray alloc]
                                 initWithContentsOfFile:[self fileLocation]];
                
                /* Now sort the numbers */
                [randomNumbers sortUsingComparator:
                 ^NSComparisonResult(id obj1, id obj2) {
                     
                     NSNumber *number1 = (NSNumber *)obj1;
                     NSNumber *number2 = (NSNumber *)obj2;
                     return [number1 compare:number2];
                     
                 }];
                
            }
        });
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([randomNumbers count] > 0){
                /* Refresh the UI here using the numbers in the
                 randomNumbers array */
            }
        });
        
    });
    
}

Performing Tasks After a Delay with GCD

/* 1 */
//- (void) printString:(NSString *)paramString{
//    NSLog(@"%@", paramString);
//}
//
//- (BOOL)            application:(UIApplication *)application
//  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//    
//    [self performSelector:@selector(printString:)
//               withObject:@"Grand Central Dispatch"
//               afterDelay:3.0];
//    
//    self.window = [[UIWindow alloc] initWithFrame:
//                   [[UIScreen mainScreen] bounds]];
//    
//    // Override point for customization after application launch.
//    self.window.backgroundColor = [UIColor whiteColor];
//    [self.window makeKeyAndVisible];
//    return YES;
//}

/* 2 */
//- (BOOL)            application:(UIApplication *)application
//  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//    
//    double delayInSeconds = 2.0;
//    
//    dispatch_time_t delayInNanoSeconds =
//    dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//    
//    dispatch_queue_t concurrentQueue =
//    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    
//    dispatch_after(delayInNanoSeconds, concurrentQueue, ^(void){
//        /* Perform your operations here */
//    });
//    
//    self.window = [[UIWindow alloc] initWithFrame:
//                   [[UIScreen mainScreen] bounds]];
//    
//    // Override point for customization after application launch.
//    self.window.backgroundColor = [UIColor whiteColor];
//    [self.window makeKeyAndVisible];
//    return YES;
//}

/* 3 */
void processSomething(void *paramContext){
    /* Do your processing here */
    NSLog(@"Processing...");
}

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    double delayInSeconds = 2.0;
    
    dispatch_time_t delayInNanoSeconds =
    dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    
    dispatch_queue_t concurrentQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_after_f(delayInNanoSeconds,
                     concurrentQueue,
                     NULL,
                     processSomething);
    
    self.window = [[UIWindow alloc] initWithFrame:
                   [[UIScreen mainScreen] bounds]];
    
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
    
    
    

}

Grouping Tasks Together with GCD

//- (BOOL)            application:(UIApplication *)application
//  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//    
//    dispatch_group_t taskGroup =  dispatch_group_create();
//    dispatch_queue_t mainQueue =  dispatch_get_main_queue();
//    
//    /* Reload the table view on the main queue */
//    dispatch_group_async(taskGroup, mainQueue, ^{
//        [self reloadTableView];
//    });
//    
//    /* Reload the scroll view on the main queue */
//    dispatch_group_async(taskGroup, mainQueue, ^{
//        [self reloadScrollView];
//    });
//    
//    /* Reload the image view on the main queue */
//    dispatch_group_async(taskGroup, mainQueue, ^{
//        [self reloadImageView];
//    });
//    
//    /* At the end when we are done, dispatch the following block */
//    dispatch_group_notify(taskGroup, mainQueue, ^{
//        /* Do some processing here */
//        [[[UIAlertView alloc] initWithTitle:@"Finished"
//                                    message:@"All tasks are finished"
//                                   delegate:nil
//                          cancelButtonTitle:@"OK"
//                          otherButtonTitles:nil, nil] show];
//        
//    });

7.17Exiting Threads and Timers

- (void) threadEntryPoint{
    
    @autoreleasepool {
        NSLog(@"Thread Entry Point");
        while ([[NSThread currentThread] isCancelled] == NO){
            [NSThread sleepForTimeInterval:4];
            if ([[NSThread currentThread] isCancelled] == NO){
                NSLog(@"Thread Loop");
            }
        }
        NSLog(@"Thread Finished");
    }
    
}

- (void) stopThread{
    
    NSLog(@"Cancelling the Thread");
    [self.myThread cancel];
    NSLog(@"Releasing the thread");
    self.myThread = nil;
    
}

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    self.myThread = [[NSThread alloc]
                     initWithTarget:self
                     selector:@selector(threadEntryPoint)
                     object:nil];
    
    [self performSelector:@selector(stopThread)
               withObject:nil
               afterDelay:3.0f];
    
    [self.myThread start];
    
    self.window = [[UIWindow alloc] initWithFrame:
                   [[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Displaying Progress with UIProgressView–1.26 NSMutableAttributedString

- (void)viewDidLoad{
    
    [super viewDidLoad];
    
    self.progressView = [[UIProgressView alloc]
                         initWithProgressViewStyle:UIProgressViewStyleBar];
    self.progressView.center = self.view.center;
    self.progressView.progress = 20.0f / 30.0f;
    [self.view addSubview:self.progressView];
    
}

Constructing and Displaying Styled Texts

//

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UILabel *label;
@end

@implementation ViewController
    
- (NSAttributedString *) attributedText{
    
    NSString *string = @"iOS SDK";
    
    NSMutableAttributedString *result = [[NSMutableAttributedString alloc]
                                         initWithString:string];
    
    NSDictionary *attributesForFirstWord = @{
                     NSFontAttributeName : [UIFont boldSystemFontOfSize:60.0f],
                     NSForegroundColorAttributeName : [UIColor redColor],
                     NSBackgroundColorAttributeName : [UIColor blackColor]
                     };
    
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = [UIColor darkGrayColor];
    shadow.shadowOffset = CGSizeMake(4.0f, 4.0f);
    
    NSDictionary *attributesForSecondWord = @{
                      NSFontAttributeName : [UIFont boldSystemFontOfSize:60.0f],
                      NSForegroundColorAttributeName : [UIColor whiteColor],
                      NSBackgroundColorAttributeName : [UIColor redColor],
                      NSShadowAttributeName : shadow
                      };
    
    /* Find the string "iOS" in the whole string and sets its attribute */
    [result setAttributes:attributesForFirstWord
                    range:[string rangeOfString:@"iOS"]];
    
    /* Do the same thing for the string "SDK" */
    [result setAttributes:attributesForSecondWord
                    range:[string rangeOfString:@"SDK"]];
    
    return [[NSAttributedString alloc] initWithAttributedString:result];
    
}
    
- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.label = [[UILabel alloc] init];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.attributedText = [self attributedText];
    [self.label sizeToFit];
    self.label.center = self.view.center;
    [self.view addSubview:self.label];
    
}

1.20 Displaying Long Lines of Text with UITextView–1.21UIButton–1.22uiimageview-UIWebView

- (void) handleKeyboardDidShow:(NSNotification *)paramNotification{
    
    /* Get the frame of the keyboard */
    NSValue *keyboardRectAsObject =
    [[paramNotification userInfo]
     objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    /* Place it in a CGRect */
    CGRect keyboardRect = CGRectZero;
    
    [keyboardRectAsObject getValue:&keyboardRect];
    
    /* Give a bottom margin to our text view that makes it
     reach to the top of the keyboard */
    self.myTextView.contentInset =
    UIEdgeInsetsMake(0.0f,
                     0.0f,
                     keyboardRect.size.height,
                     0.0f);
    
    UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
}
    
- (void) handleKeyboardWillHide:(NSNotification *)paramNotification{
    /* Make the text view as big as the whole view again */
    self.myTextView.contentInset = UIEdgeInsetsZero;
}
    
- (void) viewWillAppear:(BOOL)paramAnimated{
    [super viewWillAppear:paramAnimated];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(handleKeyboardDidShow:)
     name:UIKeyboardDidShowNotification
     object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(handleKeyboardWillHide:)
     name:UIKeyboardWillHideNotification
     object:nil];
    
    self.myTextView = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.myTextView.text = @"Some text here...";
    self.myTextView.font = [UIFont systemFontOfSize:16.0f];
    [self.view addSubview:self.myTextView];
    
}
    
- (void) viewWillDisappear:(BOOL)paramAnimated{
    [super viewWillDisappear:paramAnimated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
- (void) buttonIsPressed:(UIButton *)paramSender{
    NSLog(@"Button is pressed.");
}
    
- (void) buttonIsTapped:(UIButton *)paramSender{
    NSLog(@"Button is tapped.");
}
    
- (void)viewDidLoad{
    [super viewDidLoad];
    
    UIImage *normalImage = [UIImage imageNamed:@"NormalBlueButton"];
    UIImage *highlightedImage = [UIImage imageNamed:@"HighlightedBlueButton"];
    
    self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.myButton.frame = CGRectMake(110.0f,
                                     200.0f,
                                     100.0f,
                                     44.0f);
    
    [self.myButton setBackgroundImage:normalImage
                             forState:UIControlStateNormal];
    [self.myButton setTitle:@"Normal"
                   forState:UIControlStateNormal];
    
    [self.myButton setBackgroundImage:highlightedImage
                             forState:UIControlStateHighlighted];
    [self.myButton setTitle:@"Pressed"
                   forState:UIControlStateHighlighted];
    
    [self.myButton addTarget:self
                      action:@selector(buttonIsPressed:)
            forControlEvents:UIControlEventTouchDown];
    
    [self.myButton addTarget:self
                      action:@selector(buttonIsTapped:)
            forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.myButton];
    
}

typedef enum {
   UIViewContentModeScaleToFill,
   UIViewContentModeScaleAspectFit,
   UIViewContentModeScaleAspectFill,
   UIViewContentModeRedraw,
   UIViewContentModeCenter,
   UIViewContentModeTop,
   UIViewContentModeBottom,
   UIViewContentModeLeft,
   UIViewContentModeRight,
   UIViewContentModeTopLeft,
   UIViewContentModeTopRight,
   UIViewContentModeBottomLeft,
   UIViewContentModeBottomRight,
} UIViewContentMode;
- (void)viewDidLoad{
    [super viewDidLoad];
    
    UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir"];
    self.myImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.myImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.myImageView.image = macBookAir;
    self.myImageView.center = self.view.center;
    [self.view addSubview:self.myImageView];
}

Creating Scrollable Content with UIScrollView

- (UIImageView *) newImageViewWithImage:(UIImage *)paramImage
                                  frame:(CGRect)paramFrame{
    
    UIImageView *result = [[UIImageView alloc] initWithFrame:paramFrame];
    result.contentMode = UIViewContentModeScaleAspectFit;
    result.image = paramImage;
    return result;
    
}
    
- (void)viewDidLoad{
    [super viewDidLoad];
    
    UIImage *iPhone = [UIImage imageNamed:@"iPhone"];
    UIImage *iPad = [UIImage imageNamed:@"iPad"];
    UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir"];
    
    CGRect scrollViewRect = self.view.bounds;
    
    self.myScrollView = [[UIScrollView alloc] initWithFrame:scrollViewRect];
    self.myScrollView.pagingEnabled = YES;
    self.myScrollView.contentSize = CGSizeMake(scrollViewRect.size.width * 3.0f,
                                               scrollViewRect.size.height);
    [self.view addSubview:self.myScrollView];
    
    CGRect imageViewRect = self.view.bounds;
    UIImageView *iPhoneImageView = [self newImageViewWithImage:iPhone
                                                         frame:imageViewRect];
    [self.myScrollView addSubview:iPhoneImageView];
    
    /* Go to next page by moving the x position of the next image view */
    imageViewRect.origin.x += imageViewRect.size.width;
    UIImageView *iPadImageView = [self newImageViewWithImage:iPad
                                                       frame:imageViewRect];
    [self.myScrollView addSubview:iPadImageView];
    
    /* Go to next page by moving the x position of the next image view */
    imageViewRect.origin.x += imageViewRect.size.width;
    UIImageView *macBookAirImageView =
    [self newImageViewWithImage:macBookAir
                          frame:imageViewRect];
    [self.myScrollView addSubview:macBookAirImageView];
    
}


1.24Loading Web Pages with UIWebView

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong) UIWebView *myWebView;
@end

@implementation ViewController

/* 1 */
- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.myWebView];
    
    NSString *htmlString = @"
iOS 7 Programming Cookbook"; [self.myWebView loadHTMLString:htmlString baseURL:nil]; } /* 2 */ //- (void)viewDidLoad{ // [super viewDidLoad]; // // self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds]; // self.myWebView.scalesPageToFit = YES; // [self.view addSubview:self.myWebView]; // // NSURL *url = [NSURL URLWithString:@"http://www.apple.com"]; // NSURLRequest *request = [NSURLRequest requestWithURL:url]; // // [self.myWebView loadRequest:request]; // //} //@interface ViewController () //@property(nonatomic, strong) UIWebView *myWebView; //@end // //@implementation ViewController // ///* 3 */ //- (void)webViewDidStartLoad:(UIWebView *)webView{ // [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; //} // //- (void)webViewDidFinishLoad:(UIWebView *)webView{ // [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; //} // //- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ // [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; //} // //- (void)viewDidLoad{ // [super viewDidLoad]; // // self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds]; // self.myWebView.delegate = self; // self.myWebView.scalesPageToFit = YES; // [self.view addSubview:self.myWebView]; // // NSURL *url = [NSURL URLWithString:@"http://www.apple.com"]; // NSURLRequest *request = [NSURLRequest requestWithURL:url]; // // [self.myWebView loadRequest:request]; // //}

1.18Customizing the UILabel-UItextField

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.label = [[UILabel alloc] init];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.text = @"iOS SDK";
    self.label.font = [UIFont boldSystemFontOfSize:70.0f];
    self.label.textColor = [UIColor blackColor];
    self.label.shadowColor = [UIColor lightGrayColor];
    self.label.shadowOffset = CGSizeMake(3.0f, 3.0f);
    [self.label sizeToFit];
    self.label.center = self.view.center;
    [self.view addSubview:self.label];
    
}

1.19Inputtext

- (void)viewDidLoad{
    [super viewDidLoad];
    
    CGRect textFieldFrame = CGRectMake(38.0f,
                                       30.0f,
                                       240.0f,
                                       31.0f);
	
    self.myTextField = [[UITextField alloc]
                        initWithFrame:textFieldFrame];
    
    self.myTextField.keyboardType = UIKeyboardTypeDecimalPad;
    
    self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    self.myTextField.contentVerticalAlignment =
        UIControlContentVerticalAlignmentCenter;
    
    self.myTextField.textAlignment = NSTextAlignmentLeft;
    
    self.myTextField.placeholder = @"Enter amount here.";
    [self.view addSubview:self.myTextField];
    
    UILabel *currencyLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    currencyLabel.text = [[[NSNumberFormatter alloc] init] currencySymbol];
    currencyLabel.font = self.myTextField.font;
    [currencyLabel sizeToFit];
    self.myTextField.leftView = currencyLabel;
    self.myTextField.leftViewMode = UITextFieldViewModeAlways;
    
}

NavigationViewController in code-Navigation

[self.navigationController pushViewController:secondController
animated:YES];
[self.navigationController popViewControllerAnimated:YES];

App delegate

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    FirstViewController *viewController = [[FirstViewController alloc]
                                           initWithNibName:nil
                                           bundle:nil];
    
    self.navigationController = [[UINavigationController alloc]
                                 initWithRootViewController:viewController];
    
    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.rootViewController = self.navigationController;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

FirstViewController

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()
    @property (nonatomic, strong) UIButton *displaySecondViewController;
@end

@implementation FirstViewController
    
- (void) performDisplaySecondViewController:(id)paramSender{
    SecondViewController *secondController = [[SecondViewController alloc]
                                              initWithNibName:nil
                                              bundle:NULL];
    [self.navigationController pushViewController:secondController
                                         animated:YES];
}
    
- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"First Controller";
    
    self.displaySecondViewController = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [self.displaySecondViewController setTitle:@"Display Second View Controller"
                                      forState:UIControlStateNormal];
    [self.displaySecondViewController sizeToFit];
    self.displaySecondViewController.center = self.view.center;
    
    [self.displaySecondViewController addTarget:self
                                         action:@selector(performDisplaySecondViewController:)
                               forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.displaySecondViewController];
}

@end
- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = @"Second Controller";
}
    
- (void) goBack{
    [self.navigationController popViewControllerAnimated:YES];
}
    
- (void) viewDidAppear:(BOOL)paramAnimated{
    [super viewDidAppear:paramAnimated];
    [self performSelector:@selector(goBack)
               withObject:nil
               afterDelay:5.0f];
}

Displaying an Image on a Navigation Bar

    /* Create an Image View to replace the Title View */
    UIImageView *imageView =
    [[UIImageView alloc]
     initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 40.0f)];
    
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    /* Load an image. Be careful, this image will be cached */
    UIImage *image = [UIImage imageNamed:@"Logo"];
    
    /* Set the image of the Image View */
    [imageView setImage:image];
    
    /* Set the Title View */
    self.navigationItem.titleView = imageView;

Adding Buttons to Navigation Bars Using UIBarButtonItem

- (void)viewDidLoad{
    [super viewDidLoad];

    self.title = @"First Controller";
    
    NSArray *items = @[
                       @"Up",
                       @"Down"
                       ];
    
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]
                                            initWithItems:items];
    
    segmentedControl.momentary = YES;
    
    [segmentedControl addTarget:self
                         action:@selector(segmentedControlTapped:)
               forControlEvents:UIControlEventValueChanged];
    
UIBarButtonItem *rightBarButton =
[[UIBarButtonItem alloc] initWithCustomView:segmentedControl];

[self.navigationItem setRightBarButtonItem:rightBarButton
                                  animated:YES];
    
}
typedef NS_ENUM(NSInteger, UIBarButtonSystemItem) {
    UIBarButtonSystemItemDone,
    UIBarButtonSystemItemCancel,
    UIBarButtonSystemItemEdit,  
    UIBarButtonSystemItemSave,  
    UIBarButtonSystemItemAdd,
    UIBarButtonSystemItemFlexibleSpace,
    UIBarButtonSystemItemFixedSpace,
    UIBarButtonSystemItemCompose,
    UIBarButtonSystemItemReply,
    UIBarButtonSystemItemAction,
    UIBarButtonSystemItemOrganize,
    UIBarButtonSystemItemBookmarks,
    UIBarButtonSystemItemSearch,
    UIBarButtonSystemItemRefresh,
    UIBarButtonSystemItemStop,
    UIBarButtonSystemItemCamera,
    UIBarButtonSystemItemTrash,
    UIBarButtonSystemItemPlay,
    UIBarButtonSystemItemPause,
    UIBarButtonSystemItemRewind,
    UIBarButtonSystemItemFastForward,

1.11Presenting Custom Sharing Options with UIActivityViewController

- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    NSArray *itemsToShare = @[
                              @"Item 1",
                              @"Item 2",
                              @"Item 3",
                              ];
    
    UIActivityViewController *activity =
        [[UIActivityViewController alloc]
         initWithActivityItems:itemsToShare
         applicationActivities:@[[StringReverserActivity new]]];
    
    [self presentViewController:activity animated:YES completion:nil];
    

}

Create a new activity with a activity controller

//
//  StringReverserActivity.m
//  Presenting Custom Sharing Options with UIActivityViewController
//
//

#import "StringReverserActivity.h"

@interface StringReverserActivity () 
@property (nonatomic, strong) NSArray *activityItems;
@end

@implementation StringReverserActivity

- (void)            alertView:(UIAlertView *)alertView
    didDismissWithButtonIndex:(NSInteger)buttonIndex{
    [self activityDidFinish:YES];
}

- (NSString *) activityType{
    return [[NSBundle mainBundle].bundleIdentifier
            stringByAppendingFormat:@".%@", NSStringFromClass([self class])];
}

- (NSString *) activityTitle{
    return @"Reverse String";
}

- (UIImage *) activityImage{
    return [UIImage imageNamed:@"Reverse"];
}

- (BOOL) canPerformWithActivityItems:(NSArray *)activityItems{
    
    for (id object in activityItems){
        if ([object isKindOfClass:[NSString class]]){
            return YES;
        }
    }
    
    return NO;
    
}





- (void) prepareWithActivityItems:(NSArray *)activityItems{
    
    NSMutableArray *stringObjects = [[NSMutableArray alloc] init];
    for (id object in activityItems){
        if ([object isKindOfClass:[NSString class]]){
            [stringObjects addObject:object];
        }
    }
    
    self.activityItems = [stringObjects copy];
}

- (NSString *) reverseOfString:(NSString *)paramString{
    
    NSMutableString *reversed = [[NSMutableString alloc]
                                 initWithCapacity:paramString.length];
    
    for (NSInteger counter = paramString.length - 1;
         counter >= 0;
         counter--){
        [reversed appendFormat:@"%c", [paramString characterAtIndex:counter]];
    }
    
    return [reversed copy];
    
}

- (void) performActivity{
    
    NSMutableString *reversedStrings = [[NSMutableString alloc] init];
    
    for (NSString *string in self.activityItems){
        [reversedStrings appendString:[self reverseOfString:string]];
        [reversedStrings appendString:@"\n"];
    }
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Reversed"
                                                        message:reversedStrings
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    
    [alertView show];
    
}

@end

UISegmentedControl

Grouping Compact Options with UISegmentedControl



- (void)viewDidLoad{
    [super viewDidLoad];
	self.view.backgroundColor = [UIColor whiteColor];
    NSArray *segments = [[NSArray alloc] initWithObjects:
                         @"iPhone",
                         [UIImage imageNamed:@"iPad.png"],
                         @"iPod",
                         @"iMac", nil];

    self.mySegmentedControl = [[UISegmentedControl alloc]
                               initWithItems:segments];

    self.mySegmentedControl.segmentedControlStyle =
    UISegmentedControlStyleBezeled;
    CGRect segmentedFrame = self.mySegmentedControl.frame;
    segmentedFrame.size.height = 64.0f;
    segmentedFrame.size.width = 300.0f;
    self.mySegmentedControl.frame = segmentedFrame;

    self.mySegmentedControl.center = self.view.center;

    [self.view addSubview:self.mySegmentedControl];
    
    [self.mySegmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged   ];
}



- (void) segmentChanged:(UISegmentedControl *)paramSender{
    
    if ([paramSender isEqual:self.mySegmentedControl]){
        NSInteger selectedSegmentIndex = [paramSender selectedSegmentIndex];
        
        NSString  *selectedSegmentText =
        [paramSender titleForSegmentAtIndex:selectedSegmentIndex];
        
        NSLog(@"Segment %ld with %@ text is selected",
              (long)selectedSegmentIndex,
              selectedSegmentText);
    }
}

Result

UISegmentedControl[57033:70b] Segment 0 with iPhone text is selected
2014-01-29 22:38:31.584 Grouping Compact Options with UISegmentedControl[57033:70b] Segment 1 with (null) text is selected
2014-01-29 22:38:32.352 Grouping Compact Options with UISegmentedControl[57033:70b] Segment 2 with iPod text is selected
2014-01-29 22:38:33.336 Grouping Compact Options with UISegmentedControl[57033:70b] Segment 3 with iMac text is selected

UISlider-Customizing the UISlider

-(void)sliderChange:(UISlider *)sender{
    NSLog(@"%.0f",sender.value);
}

- (void)viewDidLoad{
    [super viewDidLoad];

    UISlider *slider =  [[UISlider alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
    
    slider.maximumValue = 100.0f;
    slider.minimumValue = 1.0f;
    slider.value = 50.0f;
    
    [self.view addSubview:slider];
    
    [slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
}

Customizing the UISlider

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UISlider *slider;
@end

@implementation ViewController

/*
 This method returns a resizable image for the
 minimum track component of the slider
 */
- (UIImage *) minimumTrackImage{
    UIImage *result = [UIImage imageNamed:@"MinimumTrack"];
    UIEdgeInsets edgeInsets;
    edgeInsets.left = 4.0f;
    edgeInsets.top = 0.0f;
    edgeInsets.right = 0.0f;
    edgeInsets.bottom = 0.0f;
    result = [result resizableImageWithCapInsets:edgeInsets];
    return result;
}

/*
 Similar to the previous method, this one returns the resizable maximum
 track image for the slider
 */
- (UIImage *) maximumTrackImage{
    UIImage *result = [UIImage imageNamed:@"MaximumTrack"];
    UIEdgeInsets edgeInsets;
    edgeInsets.left = 0.0f;
    edgeInsets.top = 0.0f;
    edgeInsets.right = 3.0f;
    edgeInsets.bottom = 0.0f;
    result = [result resizableImageWithCapInsets:edgeInsets];
    return result;
}

- (void)viewDidLoad{
    [super viewDidLoad];
	
    /* Create  the slider */
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(0.0f,
                                                             0.0f,
                                                             218.0f,
                                                             23.0f)];
    self.slider.value = 0.5;
    self.slider.minimumValue = 0.0f;
    self.slider.maximumValue = 1.0f;
    self.slider.center = self.view.center;
    [self.view addSubview:self.slider];
    
    /* Change the minimum value image */
    [self.slider setMinimumValueImage:[UIImage imageNamed:@"MinimumValue"]];
    
    /* Change the minimum track image */
    [self.slider setMinimumTrackImage:[self minimumTrackImage]
                             forState:UIControlStateNormal];
    
    /* Change the thumb image for both untouched and touched states */
    [self.slider setThumbImage:[UIImage imageNamed:@"Thumb"]
                      forState:UIControlStateNormal];
    [self.slider setThumbImage:[UIImage imageNamed:@"Thumb"]
                      forState:UIControlStateHighlighted];
    
    /* Change the maximum track image */
    [self.slider setMaximumTrackImage:[self maximumTrackImage]
                             forState:UIControlStateNormal];
    
    /* Change the maximum value image */
    [self.slider setMaximumValueImage:[UIImage imageNamed:@"MaximumValue"]];
    
}

UISwitch And Target//Customizing the UISwitch

- (void) switchIsChanged:(UISwitch *)paramSender{
    
    NSLog(@"Sender is = %@", paramSender);
    
    if (paramSender.isOn){
        NSLog(@"The switch is turned on.");
    } else {
        NSLog(@"The switch is turned off.");
    }
    
}
- (IBAction)turn:(UISwitch *)sender {
    if (self.seSwitch.isOn) {
        NSLog(@"The switch is turned on.");
    }else{
        NSLog(@"The switch is turned off.");
    }

}

- (void)viewDidLoad{
    [super viewDidLoad];

    
    /* Create the switch */
    self.mySwitch = [[UISwitch alloc] initWithFrame:
                     CGRectMake(100, 100, 0, 0)];
    [self.mySwitch setOn:YES];
    [self.view addSubview:self.mySwitch];
    
    [self.mySwitch addTarget:self
                      action:@selector(switchIsChanged:)
            forControlEvents:UIControlEventValueChanged];
    
}

Customizing the UISwitch

@interface ViewController ()
@property (nonatomic, strong) UISwitch *mainSwitch;
@end

@implementation ViewController

/* 1 */
//- (void)viewDidLoad
//{
//    [super viewDidLoad];
//	// Do any additional setup after loading the view, typically from a nib.
//
//    /* Create the switch */
//    self.mainSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
//    self.mainSwitch.center = self.view.center;
//    [self.view addSubview:self.mainSwitch];
//
//    /* Customize the switch */
//
//    /* Adjust the off-mode tint color */
//    self.mainSwitch.tintColor = [UIColor redColor];
//    /* Adjust the on-mode tint color */
//    self.mainSwitch.onTintColor = [UIColor brownColor];
//    /* Also change the knob's tint color */
//    self.mainSwitch.thumbTintColor = [UIColor greenColor];
//
//}

/* 2 */
/* Note: This is only for iOS 6 and older */
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    /* Create the switch */
    self.mainSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
    self.mainSwitch.center = self.view.center;
    /* Make sure the switch won't appear blurry on iOS Simulator */
    [self.view addSubview:self.mainSwitch];
    
    /* Customize the switch */
    self.mainSwitch.onImage = [UIImage imageNamed:@"On"];
    self.mainSwitch.offImage = [UIImage imageNamed:@"Off"];
    
}

PHP+mysql

while ($row = mysql_fetch_array($result)) {

	@$all[] =  array("id"=>$row[id],"username"=>$row[username],"useremail"=>$row[useremail],"textfield"=>$row[textfield]);
}
@$json = json_encode($all);
print_r($json);

在PHP输出的结果 :

[{"id":"1","username":"","useremail":"","textfield":""},{"id":"2","username":"","useremail":"","textfield":""},{"id":"3","username":"1","useremail":"2","textfield":"3"},{"id":"4","username":"1","useremail":"2","textfield":"3"},{"id":"5","username":"1","useremail":"2","textfield":"3"},{"id":"6","username":"aa","useremail":"aatextfield=Aa","textfield":""},{"id":"7","username":"ff","useremail":"fff","textfield":"F"}]

在xcode输出的结果:

GuestBook[42138:4207] this is (
        {
        id = 1;
        textfield = "";
        useremail = "";
        username = "";
    },
        {
        id = 2;
        textfield = "";
        useremail = "";
        username = "";
    },
        {
        id = 3;
        textfield = 3;
        useremail = 2;
        username = 1;
    },
        {
        id = 4;
        textfield = 3;
        useremail = 2;
        username = 1;
    },
        {
        id = 5;
        textfield = 3;
        useremail = 2;
        username = 1;
    },
        {
        id = 6;
        textfield = "";
        useremail = "aatextfield=Aa";
        username = aa;
    },
        {
        id = 7;
        textfield = F;
        useremail = fff;
        username = ff;
    }
)

while ($row=mysql_fetch_row($result)) {
	$myrow = json_encode($row);
	echo "$myrow";
	
}

$mjson = json_encode($myrow);
echo "$mjson";

?>

结果

["1","","",""]["2","","",""]["3","1","2","3"]["4","1","2","3"]["5","1","2","3"]["6","aa","aatextfield=Aa",""]["7","ff","fff","F"]
while ($row=mysql_fetch_row($result)) {
	print_r($row);
	$myrow = json_encode($row);

	$all[] = "id = $row[0],username = $row[1], useremail = $row[2], textfield = $row[3]";
	
}
echo "
"; echo "
"; echo "$myrow"; echo "
"; echo "
"; print_r($all); echo "
"; $json = json_encode($all); echo "...$json"; ?>

结果

Array ( [0] => 1 [1] => [2] => [3] => ) Array ( [0] => 2 [1] => [2] => [3] => ) Array ( [0] => 3 [1] => 1 [2] => 2 [3] => 3 ) Array ( [0] => 4 [1] => 1 [2] => 2 [3] => 3 ) Array ( [0] => 5 [1] => 1 [2] => 2 [3] => 3 ) Array ( [0] => 6 [1] => aa [2] => aatextfield=Aa [3] => ) Array ( [0] => 7 [1] => ff [2] => fff [3] => F ) 

["7","ff","fff","F"]

Array ( [0] => id = 1,username = , useremail = , textfield = [1] => id = 2,username = , useremail = , textfield = [2] => id = 3,username = 1, useremail = 2, textfield = 3 [3] => id = 4,username = 1, useremail = 2, textfield = 3 [4] => id = 5,username = 1, useremail = 2, textfield = 3 [5] => id = 6,username = aa, useremail = aatextfield=Aa, textfield = [6] => id = 7,username = ff, useremail = fff, textfield = F ) 


...["id = 1,username = , useremail = , textfield = ","id = 2,username = , useremail = , textfield = ","id = 3,username = 1, useremail = 2, textfield = 3","id = 4,username = 1, useremail = 2, textfield = 3","id = 5,username = 1, useremail = 2, textfield = 3","id = 6,username = aa, useremail = aatextfield=Aa, textfield = ","id = 7,username = ff, useremail = fff, textfield = F"]
Example #6 Accessing array elements

 "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
The above example will output:

string(3) "bar"
int(24)
string(3) "foo"
delete from mem where id = $id

select * from mem where id = $id

update mem set name = '$name', password = '$passwd', ip = '$ip', last_time = '$last_time' where id = $id

insert into mem values('','$name','$password','$ipip','$last')


";
echo "";
echo "ID";
echo "nicker";
echo "password";
echo "gender";
echo "";

while ($row = mysql_fetch_array($result)) {
echo "";
echo "$row[id]";
echo "$row[nicker]";
echo "$row[password]";
echo "$row[gender]";
echo "";

}



if (!$id) {
	;
}
echo "";




?>

3 2 1