OC Learning Article---Other classes in the foundation Framework (nsnumber,nsdate,nsexcetion)

Source: Internet
Author: User
Tags date1 time zones set time unpack

The previous article mentioned the Nsdirctionary class in the foundation framework: http://blog.csdn.net/jiangwei0910410003/article/details/ 41830179, these one by one articles look at the other common classes of foundation: nsnumber,nsdate,nsexception

Note: In fact, according to the idea of the collection in Java, there should be a set, yes, OC has Nsset and nsmutableset these two classes, but, here why I do not introduce alone? Because his operation and Nsarray are very similar, but he and Nsarray have a difference is that he can not put data duplication, and he is also disorderly. Nothing else, so it is not introduced separately, and Nsset in the subsequent development process may not use a lot.


1, NSNumber

This class is mainly used to encapsulate the basic types, and here we have to say:

The collection in OC is not allowed to deposit the basic type, so the NSNumber class is born, need to encapsulate the basic type, and then stored in, this is similar to Java in the automatic boxing and unpacking, Java collection is not allowed to deposit the basic type, but we can still see the operation, Just because of the auto-boxing feature, if you change the JDK of Eclipse to 5.0, you can see how it's going to work.

Note: Why can't the basic type be stored in the collection?

The reason is that the methods in the collection element are manipulated when the collection is manipulated, but there is no method for the base type.

From this point we can see that the nsnumber is very important, the latter will be used frequently.

main.m//21_nsnumber////Created by Jiangwei on 14-10-12.//Copyright (c) 2014 Jiangwei. All rights reserved.//#import <foundation/foundation.h>//wrapper basic data type int main (int argc, const char * argv[]) {@autor        Eleasepool {//1.----------------create NSNumber//packet NSNumber *intnumber = [NSNumber numberwithint:3];        NSNumber *floatnumber = [NSNumber numberwithfloat:9.8f];                Nsarray *array = @[intnumber,floatnumber];        unpacking int value = [Intnumber intvalue];        float values = [Floatnumber floatvalue];                NSString *str = [Intnumber stringvalue];                        Optimization syntax NSNumber *intnumbers = @12;        How to deposit a struct in an array//use Nsvalue to encapsulate a struct//nsvalue is nsnumber parent//Packet Nsrange rang = {1,3};                Nsvalue *v = [Nsvalue Valuewithrange:rang];                        Unpacking rang = [v rangevalue];            A custom structure is encapsulated in a struct wxpoint{float x; FloAt Y;                };        struct Wxpoint p = {50,100};                The first parameter is the variable address of the struct, the second parameter is the type nsvalue *v1 = [Nsvalue value:&p withobjctype: @encode (struct wxpoint)];        Unpacking the struct wxpoint p1;                        [V1 getvalue:&p1];        Nsnull use//array is no way to store an empty object of nil//nsarray *nilarray = @[nil,nil,nil];//Error//Sometimes we need to put an empty object in the array needs        NSNull *n1 = [NSNull null];        NSNull *n2 = [NSNull null];        Nsarray *nullarray = @[n1,n2];                    NSLog (@ "Nullarray =%@", Nullarray); } return 0;}


1, Package and package

1.----------------Create nsnumber//packet nsnumber *intnumber = [NSNumber numberwithint:3]; NSNumber *floatnumber = [NSNumber numberwithfloat:9.8f]; Nsarray *array = @[intnumber,floatnumber];//unpack int value = [Intnumber intvalue];float values = [Floatnumber floatValue]; NSString *str = [Intnumber stringvalue];
There are basic types of methods in the NSNumber class that can be manipulated, but it is worth mentioning that:

NSString *str = [Intnumber stringvalue]; NSLog (@ "%@", str);
we see that the intnumber is wrapped in int type, but we can use the StringValue method to unpack, this is equivalent to the conversion of int type to NSString type, this needs to be noted, the same can be done in turn.

Operation Result:



2. Optimize the way to create

Optimization syntax NSNumber *intnumbers = @12;
It looks similar to the way you create strings.


3, the structure of the type of automatic packaging and reconciliation package

How to deposit a struct in an array//use Nsvalue to encapsulate a struct//nsvalue is nsnumber parent//Packet Nsrange rang = {1,3}; Nsvalue *v = [Nsvalue valuewithrange:rang];//unpacking rang = [v rangevalue];
In OC There is also a struct type, and he cannot be directly deposited into the collection class, when he is encapsulated NsvalueClass, not the NSNumber class.


4. Automatic package and package for custom structure type

A custom structure is encapsulated in a struct wxpoint{    float x;    float y;}; struct Wxpoint p = {50,100};//The first parameter is the variable address of the struct, the second argument is the type nsvalue *v1 = [Nsvalue value:&p withobjctype: @encode (struct Wxpoint)];//to unpack the struct wxpoint p1; [V1 getvalue:&p1];
For a custom struct type, we need to use the Value:withobjctype: method to do this when the packet is being marshaled, and we need to use the@encode (struct wxpoint)Passed in, this function is equivalent to the structure of the type passed through.

Remember: You need to pass a struct type when you are marshaling a custom struct type


5. Encapsulation of NULL values

Nsnull use//array is no way to store an empty object Nil//nsarray *nilarray = @[nil,nil,nil];//Error//Sometimes we need to put an empty object in the array requirements nsnull *N1 = [ NSNull NULL]; NSNull *n2 = [NSNull null]; Nsarray *nullarray = @[n1,n2]; NSLog (@ "Nullarray =%@", Nullarray);
First, let's look at why there is a need to put a null value into the collection, and we'll talk about the application later.

Then we need to use NSNull to pack and package.


Second, NSDate

This class is the class of operation date in OC, he is also a lot of useful, and later will say timer, will use this class

main.m//22_nsdate////Created by Jiangwei on 14-10-12.//Copyright (c) 2014 Jiangwei.  All rights reserved.//#import <foundation/foundation.h>int Main (int argc, const char * argv[]) {@autoreleasepool {//1.----------------creation Date NSDate *date = [NSDate date];//represents the current point in time nsdate *date1 = [[NSDate alloc] I        NIT];                NSLog (@ "%@", date);                Date1 = [NSDate datewithtimeintervalsincenow:1000];//Unit is the second, at the current time plus 1000s, if it is minus a time, the direct use of negative values can be NSLog (@ "%@", date);                 Timestamp: A difference between a date and 1970 years, this value is very large nsdate *date2 = [nsdate datewithtimeintervalsince1970:1000];//parameter is the size of the timestamp        Create a date and then get the timestamp nsdate *now = [NSDate Date];        Nstimeinterval interval = [now timeIntervalSince1970];        Interval = [now timeintervalsincenow];//a difference to the current time//date comparison//by invoking the Date object's compare, or by a difference between two dates        Nscomparisonresult result = [date compare:date1];  if (result = = nsorderedascending) {//greater than      }else if (result = = nsordereddescending) {//less than}else{//equals}        Date formatting NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];        [Dateformatter setdateformat:@ "Yyyy-mm-dd HH:mm:ss"];        NSString *str = [Dateformatter stringfromdate:date];                        NSLog (@ "%@", str);        Set time zone Nstimezone *timezone = [Nstimezone timezonewithname:@ "America/new_york"];                [Dateformatter Settimezone:timezone];                The following method is to add and subtract a time zone value from the green time zone (green time zone is 0)//[nstimezone timezoneforsecondsfromgmt:0];            By printing you can get the specific time zone nsarray *array = [Nstimezone knowntimezonenames];//get all time zones for (NSString *str in array) {        NSLog (@ "%@", str);        }//Convert string to date object NSString *strs = @ "December 14, 2013 16:31:08";        [Dateformatter setdateformat:@ "yyyy mm month DD day HH:MM:SS"];                    Date1 = [Dateformatter datefromstring:strs];  }  return 0;} 

1. Create a date

The default is the current time

1.----------------Creation date NSDate *date = [NSDate date];//represents the current point in time nsdate *date1 = [[NSDate alloc] init]; NSLog (@ "%@", date);


2, increase or decrease the time point

Date1 = [NSDate datewithtimeintervalsincenow:1000];//Unit is the second, at the current time plus 1000s, if it is minus a time, the direct use of negative values can be NSLog (@ "%@", date);
Method is one, if it is minus the point of time, directly with a negative value


3, from 1970 onwards to the present time stamp

Timestamp: A difference between a date and 1970 years, this value is very large nsdate *date2 = [nsdate datewithtimeintervalsince1970:1000];//parameter is the size of the timestamp
There is a special time in the computer: 1970, this is the start point of the timestamp, and the system clock is calculated relative to this point in time.


4. Create a date and then get his timestamp

Create a date and then get the timestamp nsdate *now = [NSDate Date]; Nstimeinterval interval = [now timeintervalsince1970];interval = [present timeintervalsincenow];//to a difference of current time
This timestamp is compared with 1970, how much earlier than he value, this is commonly known as the timestamp


5. Comparison of dates

Date comparison//By invoking the compare of a Date object, or by a difference between two dates nscomparisonresult result = [Date compare:date1];if (Result = = nsorderedascending) {    //greater than}else if (result = = nsordereddescending) {    //less than}else{    //equals}


6. Date formatting (date converted to string)

Date formatting NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init]; [Dateformatter setdateformat:@ "Yyyy-mm-dd HH:mm:ss"]; NSString *str = [Dateformatter stringfromdate:date]; NSLog (@ "%@", str);


7. Set the time zone

Set time zone Nstimezone *timezone = [Nstimezone timezonewithname:@ "America/new_york"]; [Dateformatter Settimezone:timezone];
But what do we get when we see this time zone value? Impossible to memorize? Here, we can print a value:

The following method is to add and subtract a time zone value from the green time zone (green time zone is 0)//[nstimezone timezoneforsecondsfromgmt:0];//by printing can get the specific time zone nsarray *array = [ Nstimezone knowntimezonenames];//gets all the time zones for (NSString *str in array) {    NSLog (@ "%@", str);}
This allows us to obtain a specific time zone value:



8. Convert a string into a date

Converts a string into a Date object nsstring *strs = @ "December 14, 2013 16:31:08"; [Dateformatter setdateformat:@ "yyyy mm month DD Day HH:MM:SS"];d ate1 = [Dateformatter datefromstring:strs];


Third, NSException

This class, like the exception class in Java, is used to catch exceptions, increase the robustness of the program, and use it simply as follows:

  main.m//  23_exception////  Created by Jiangwei on 14-10-12.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import <foundation/foundation.h>int Main (int argc, const char * argv[]) {    @ Autoreleasepool {       //catch exception        @try {            int a = 1/0;        }        @catch (NSException *exception) {                    }        @finally {                    }    }    return 0;}


Summary

This article introduces three commonly used classes in the foundation framework: nsnumber/nsdate/nsexception, so here we have an explanation of the class in the foundation, in fact, there are other classes in the foundation, The back will be used, with more natural to know how he used.














OC Learning Article---Other classes in the foundation Framework (nsnumber,nsdate,nsexcetion)

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.