Dark Horse programmer ------ various data types in the Foundation framework, dark horse programmer

Source: Internet
Author: User

Dark Horse programmer ------ various data types in the Foundation framework, dark horse programmer

----- IOS training, Android training, and Java training. We look forward to communicating with you -----


1. Structure of nsange, NSPoint \ CGPoint, NSSize \ CGSize, NSRect \ CGRect (CGPint CGSize)

1) nsange

Nsange indicates a range. For example, we want to obtain an @ "I fall in love with Objective-C ~"; In this string, "love" indicates that the range is from 11 and the length is 4;

The essence of nsange is a struct,

It contains the location and length attributes, indicating the location and length respectively.

There are many ways to define a nsange variable, as listed below:


This method is generally not used and is too readable.

<Span style = "font-size: 14px;"> nsange r1 = {2, 4}; // No </span>


This method is not recommended, and the readability is poor.

Nsange r2 = {. location = 2,. length = 4}; // No


This method is commonly used and requires the following:
NSRange r3 = NSMakeRange(2, 4);

Here is an example:



2) NSPoint \ CGPoint

NSPoint and CGPoint are synonyms (the following are synonyms). During Development, we often use CGPoint;

CGPoint indicates a vertex,

Internal Structure:

Struct CGPoint {

CGFloat x;

CGFloat y;

};

Definition method:

CGPoint p1 = NSMakePoint (10, 10); // NSPoint p2 = CGPointMake (20, 20); // The most common

// Indicates the origin. // CGPointZero = CGPointMake (0, 0)

// Convert the struct into a string // NSString * str = NSStringFromPoint (p1 );


3)NSSize \ CGSize

As the name suggests, CGSize definitely indicates a size, and its internal structure is:

Struct CGSize {

CGFloat width;

CGFloat height;

};

Typedef struct CGSize;

Define a CGSize

 NSSize s1 = CGSizeMake(100, 50);    NSSize s2 = NSMakeSize(100, 50);    CGSize s3 = NSMakeSize(200, 60);
Set Convert CGSize to string:

NSString *str = NSStringFromSize(s3);

4)NSRect \ CGRect (CGPoint CGSize)

NSRect can be seen from its surface. It represents a rectangle. In fact, its internal structure is CGPoint and CGSize;

Define a CGRect:

 CGRect r1 = CGRectMake(0, 0, 100, 50);        CGRect r2 = { {0, 0}, {100, 90}};    

CGPoint p1 = NSMakePoint (10, 10); NSSize s2 = NSMakeSize (100, 50); CGRect r3 = {p1, s2 }; // The premise of using CGPointZero is to add the CoreGraphics framework CGRect r4 = {CGPointZero, CGSizeMake (100, 90 )};

Convert a struct to a string:

NSString *str = NSStringFromRect(r1);


Ii. NSString and NSMutableString

Obviously, this represents a string.

Creation Method:

 NSString *s1 = @"jack";        //NSString *s2 = [[NSString alloc] initWithString:@"jack"];        NSString *s3 = [[NSString alloc] initWithFormat:@"age is %d", 10];

C string to OC string:

 NSString *s4 = [[NSString alloc] initWithUTF8String:"jack"];

Convert the OC string to a C string:

 const char *cs = [s4 UTF8String];

NSUTF8StringEncoding can be used in Chinese.

NSString *s5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/1.txt" encoding:NSUTF8StringEncoding error:nil];


Convert a URL to an NSString:

// Note the differences between the two writing methods // NSURL * url = [[NSURL alloc] initWithString: @ "file: // Users/apple/Desktop/1.txt"]; NSURL * url = [NSURL fileURLWithPath: @ "/Users/apple/Desktop/1.txt"]; NSString * s6 = [[NSString alloc] initWithContentsOfURL: url encoding: Unknown error: nil]; NSLog (@ "s6 = \ n % @", s6 );

Write a string to a file.:

// WriteToFile: the file name atomically: YES indicates the atomic operation, NO. Otherwise // encoding: encoding [@ "Jack \ nJack" writeToFile: @ "/Users/apple/Desktop/my.txt" atomically: YES encoding: NSUTF8StringEncoding error: nil];


Write the string to the file using the URL:

 NSString *str = @"4234234";    NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/my2.txt"];    [str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];


NSMutableString indicates the string that can be modified:

This means that you can add, delete, modify, and query data.

NSMutableString * s1 = [NSMutableString stringWithFormat: @ "my age is 10"]; // splice the content to the end of s1 [s1 appendString: @ "11 12"]; // obtain the range of is: nsange range = [s1 rangeOfString: @ "is"]; // Delete the string of this range [s1 deleteCharactersInRange: range]; // NSString * s2 = [NSString stringWithFormat: @ "age is 10"]; // note that s2 is still s2 at this time, s3 and s2 are two strings: NSString * s3 = [s2 stringByAppendingString: @ "11 12"];




Iii. NSArray and NSMutableArray

For the demo, a class is declared and defined first:

<span style="font-size:14px;">#import <Foundation/Foundation.h>@interface Person : NSObject@end</span>

<span style="font-size:14px;">#import "Person.h"@implementation Person@end</span>


NSArray is clearly an array, but it can only store OC object types, not basic data types;

. NSArray Creation

<span style="font-size:14px;"> NSArray *array2 = [NSArray arrayWithObject:@"jack"];</span>


This array is always an empty array.
<span style="font-size:14px;">NSArray *array = [NSArray array];</span>


Nil is the end mark of the array element.

<span style="font-size:14px;"> NSArray *array3 = [NSArray arrayWithObjects:@"jack", @"rose", nil];</span>


Number of NSArray Elements

<span style="font-size:14px;">NSLog(@"%ld", array3.count);</span>


Access to elements in NSArray

 NSLog(@"%@", [array3 objectAtIndex:1]);        //array3[1];    NSLog(@"%@", array3[0]);


Traverse the array:

Method 1: (using the traditional for loop)

<span style="font-size:14px;">Person *p = [[Person alloc] init];        NSArray *array = @[p, @"rose", @"jack"];        for (int i = 0; i<array.count; i++)      {         NSLog(@"%@", array[i]);       }</span>

Method 2: (use an enhanced for loop)

// Id obj represents each element in the array int I = 0; for (id obj in array) {// locate the position of the obj element in the array NSUInteger I = [array indexOfObject: obj]; NSLog (@ "% ld-% @", I, obj); I ++; if (I = 1) {break ;}}


Method 3: (using code blocks)

[Array enumerateObjectsUsingBlock: // each time an element is traversed, a block is called. // The current element and index position are passed as parameters to the block ^ (id obj, NSUInteger idx, BOOL * stop) {NSLog (@ "% ld-% @", idx, obj); if (idx = 0) {// stop traversal * stop = YES;}];



Basic use of NSMutableArray variable array

NSMutableArray * array = [NSMutableArray arrayWithObjects: @ "rose", @ "jim", nil]; // Add the element [array addObject: [[Person alloc] init]; [array addObject: @ "jack"]; // delete an element // [array removeAllObjects]; // delete a specified object // [array removeObject: @ "jack"]; [array removeObjectAtIndex: 0]; // incorrect syntax // [array addObject: nil];


NSArray quick creation method:

@ [] Only create an unchangeable array NSArray

/* NSMutableArray * array = @ [@ "jack", @ "rose"]; [array addObject: @ "jim"]; */NSArray * array = @ [@ "jack", @ "rose"];



Iv. NSSet and NSMutableSet

Comparison between NSSet and NSArray
1> commonalities
* All are collections and can store multiple OC objects.
* Only OC objects can be stored, not non-OC object types (basic data types: int, char, float, struct, enumeration)
* They are both immutable and each has a mutable subclass.
 
2> Differences
* NSArray has sequence, and NSSet has no sequence.

Basic use of set

NSSet * s = [NSSet set]; NSSet * s2 = [NSSet setWithObjects: @ "jack", @ "rose", @ "jack2", @ "jack3", nil]; // randomly extract an element NSString * str = [s2 anyObject];


Use of NSMutbaleSet:

NSMutableSet * s = [NSMutableSet set]; // Add the element [s addObject: @ "hack"]; // Delete the element // [s removeObject: <# (id) #>];


5. NSDirectory and NSMutableDictionary

As the name suggests, this is a dictionary, where the data structure is in the form of a key-value pair;

Dictionary:

Key ----> value
Index ----> text content

Everything stored in it is a key-value pair.

Creation method:

// NSDictionary * dict = [NSDictionary dictionaryWithObject: @ "jack" forKey: @ "name"]; // NSArray * keys = @ [@ "name ", @ "address"]; // NSArray * objects = @ [@ "jack", @ "Beijing"]; // NSDictionary * dict = [NSDictionary dictionaryWithObjects: objects forKeys: keys];/* NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys: @ "jack", @ "name", @ "Beijing", @ "address", @ "32423434 ", @ "qq", nil]; */NSDictionary * dict =@ {@ "name": @ "jack", @ "address": @ "Beijing "}; // id obj = [dict objectForKey: @ "name"]; id obj = dict [@ "name"]; NSLog (@ "% @", obj ); // return the number of key-value pairs NSLog (@ "% ld", dict. count );

Use of NSMutableDictionary:

NSMutableDictionary * dict = [NSMutableDictionary dictionary]; // Add a key-Value Pair [dict setObject: @ "jack" forKey: @ "name"]; [dict setObject: @ "Beijing" forKey: @ "address"]; [dict setObject: @ "rose" forKey: @ "name"]; // remove a key-Value Pair // [dict removeObjectForKey: <# (id) #>]; NSString * str = dict [@ "name"];


Vi. NSNumber and NSValue

It can replace a basic data type with the OC object type. We know that the basic data type cannot be used in both NSArray and NSDirectory. Thus, its function comes.


Convert the basic data type to the NSNumber type:

<span style="font-size:14px;">NSNumber *num = [NSNumber numberWithInt:10];</span>
<Span style = "font-size: 14px;"> // wrap various basic data types into NSNumber objects @ 10.5; @ YES; @ 'a '; // NSNumber object @ "A"; // NSString object </span>


  Wrap age variables into NSNumber objects
Int age = 100;
@ (Age );
<span style="font-size:14px;">[NSNumber numberWithInt:age];</span>


NSNumber can wrap the basic data type as an object because it inherits NSValue


Struct ---> OC object

<Span style = "font-size: 14px;"> CGPoint p = CGPointMake (10, 10); // convert the struct into the Value object NSValue * value = [NSValue valueWithPoint: p]; </span>


Convert value to the corresponding struct

[value pointValue];
NSArray *array = @[value ];



VII. NSDate

When processing data of the date type, it is often tricky to use struct operations. Therefore, NSDate came into being.


Create a time object
NSDate * date = [NSDate date];
The printed time is the time of the 0 time zone (Beijing-East 8)
NSLog (@ "% @", date );

NSDate * date2 = [NSDate dateWithTimeInterval: 5 sinceDate: date];


The number of seconds that have elapsed since 1970.
NSTimeInterval seconds = [date2 timeIntervalSince1970];

[Date2 timeIntervalSinceNow];


Convert a date to a string:

<Span style = "font-size: 14px;"> // create a time object NSDate * date = [NSDate date]; // print out the NSLog (@ "% @", date) of the Time Zone 0 (Beijing-East 8); NSDate * date2 = [NSDate dateWithTimeInterval: 5 sinceDate: date]; // the number of seconds that have elapsed since 1970 NSTimeInterval seconds = [date2 timeIntervalSince1970]; // [date2 timeIntervalSinceNow]; </span>

Convert a date to a date type:

<span style="font-size:14px;"> // 09/10/2011    NSString *time = @"2011/09/10 18:56";        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    formatter.dateFormat = @"yyyy/MM/dd HH:mm";        NSDate *date = [formatter dateFromString:time];    NSLog(@"%@", date);</span>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.