Examples of basic usages of nsarray in Objective-c _ios

Source: Internet
Author: User

Sort of Nsarray

Copy Code code as follows:

+ (ID) studentwithfirstname: (NSString *) firstName lastName: (NSString *) lastname{

Student *stu = [[Student alloc] init];

Stu.firstname = FirstName;
Stu.lastname = LastName;

return Stu;
}

+ (ID) studentwithfirstname: (NSString *) firstName lastName: (NSString *) lastName bookname: (NSString *) bookname{

Student *stu = [Student studentwithfirstname:firstname lastname:lastname];

Stu.book = [book Bookwithname:bookname];

return Stu;

}

-(Nscomparisonresult) Comparestudent: (Student *) stu{

Nscomparisonresult result = [Self.firstname compare:stu.firstName];

if (result = = Nsorderedsame) {
result = [Self.lastname compare:stu.lastName];
}

return result;

}

-(NSString *) description{

return [NSString stringwithformat:@ "%@%@%@", Self.firstname,self.lastname,self.book.name];
return [NSString stringwithformat:@ "%@%@%@", Self.firstname,self.lastname,_book.name];
}


#pragma mark 3.NSArray Sort 1
void ArraySort1 () {

Nsarray *array = [Nsarray arraywithobjects:@ "2", @ "3", @ "1", @ "4", nil Nil];

A comparison method for specifying the system's own rules compare:
Nsarray *array2 = [Array sortedarrayusingselector: @selector (compare:)];
NSLog (@ "%@", array2);

}

#pragma mark 3.NSArray Sort 2
void ArraySort2 () {

Student *STU1 = [Student studentwithfirstname:@ "Hu" lastname:@ "Mingtao"];
Student *STU2 = [Student studentwithfirstname:@ "Zhu" lastname:@ "Wenpeng"];
Student *STU3 = [Student studentwithfirstname:@ "Zhao" lastname:@ "Weisong"];
Student *stu4 = [Student studentwithfirstname:@ "Hu" lastname:@ "Junpeng"];

Nsarray *array = [Nsarray arraywithobjects:stu1,stu2,stu3,stu4, nil Nil];

Like CompareTo in Java, you define the comparison, but you must implement the Compare method
Nsarray *array2 = [Array sortedarrayusingselector: @selector (comparestudent:)];

NSLog (@ "%@", array2);

}

#pragma mark 3.NSArray sort 3-block Sorting
void ArraySort3 () {

Student *STU1 = [Student studentwithfirstname:@ "Hu" lastname:@ "Mingtao"];
Student *STU2 = [Student studentwithfirstname:@ "Zhu" lastname:@ "Wenpeng"];
Student *STU3 = [Student studentwithfirstname:@ "Zhao" lastname:@ "Weisong"];
Student *stu4 = [Student studentwithfirstname:@ "Hu" lastname:@ "Junpeng"];

Nsarray *array = [Nsarray arraywithobjects:stu1,stu2,stu3,stu4, nil Nil];

Nsarray *array2 = [Array Sortedarrayusingcomparator:^nscomparisonresult (Student *obj1, Student *obj2) {
Nscomparisonresult result = [Obj1.firstname compare:obj2.firstName];

if (result = = Nsorderedsame) {
result = [Obj1.lastname compare:obj2.lastName];
}

return result;
}];

NSLog (@ "%@", array2);


}

#pragma mark 4.NSArray Sort 4-advanced sort
void ArraySort4 () {

Student *STU1 = [Student studentwithfirstname:@ "Hu" lastname:@ "Mingtao" bookname:@ "Lianai"];
Student *STU2 = [Student studentwithfirstname:@ "Zhu" lastname:@ "Wenpeng" bookname:@ "Tianshi"];
Student *STU3 = [Student studentwithfirstname:@ "Zhao" lastname:@ "Weisong" bookname:@ "Love"];
Student *stu4 = [Student studentwithfirstname:@ "Hu" lastname:@ "Junpeng" bookname:@ "Qingren"];

Nsarray *array = [Nsarray arraywithobjects:stu1,stu2,stu3,stu4, nil Nil];

1. First sort by title
Nssortdescriptor *booknamedesc = [Nssortdescriptor sortdescriptorwithkey:@ "Book.name" Ascending:YES];
2. Sort by last name first
Nssortdescriptor *firstnamedesc = [Nssortdescriptor sortdescriptorwithkey:@ "FirstName" ascending:yes];
3. Sort by First Name
Nssortdescriptor *lastnamedesc = [Nssortdescriptor sortdescriptorwithkey:@ "LastName" ascending:yes];

Nsarray *array2 = [Array Sortedarrayusingdescriptors:[nsarray arraywithobjects:booknamedesc,firstnamedesc, Lastnamedesc, nil Nil]];

NSLog (@ "%@", array2);


}


some usages of Nsarray
Nsarray only allows OC objects, and cannot load null values, empty represents the end of an array element

Copy Code code as follows:

Basic usage of #pragma mark-nsarray
Create an empty array
Nsarray *array = [Nsarray array];
To create an array with an element
Array = [Nsarray arraywithobject:@ "123"];
To create an array with multiple elements
Array = [Nsarray arraywithobjects:@ "a", @ "B", nil];//cannot install nil null pointer, null value represents end of array element
Assigns an array to an array
+ (Instancetype) Arraywitharray: (Nsarray *) array;
Get the number of elements
int count = [array count]; and count = Array.count; The same is called the Get method
Whether to include an element
-(BOOL) Containsobject: (ID) anobject;
Returns the last element
-(ID) lastobject;
Gets the element of the index position
-(ID) Objectatindex: (Nsuinteger) index;
Get the location of the element
-(Nsuinteger) Indexofobject: (ID) anobject;
Find the location of an element in range range
-(Nsuinteger) Indexofobject: (ID) anobject inrange: (nsrange) range;
Compare two collection contents to be identical
-(Bool) Isequaltoarray: (Nsarray *) Otherarray;
Returns the first identical object element in a two collection
-(ID) Firstobjectcommonwitharray: (Nsarray *) Otherarray;

Advanced usage of #pragma mark-nsarray
So that all the elements in the collection are executed Aselector this method
-(void) Makeobjectsperformselector: (SEL) Aselector;
Let all elements in the collection execute Aselector this method, add parameters to this method, but only one argument is supported
-(void) Makeobjectsperformselector: (SEL) Aselector withobject: (ID) argument
Adds an element that returns a new Nsarray (the method caller itself has not changed)
-(Nsarray *) Arraybyaddingobject: (ID) anobject
Adds all the elements of the Otherarray, returns a new Nsarray (method does not change itself)
-(Nsarray *) Arraybyaddingobjectsfromarray: (Nsarray *) Otherarray;
To intercept an array of range ranges
-(Nsarray *) Subarraywithrange: (nsrenge) range;
Use separator as a concatenation character, stitching into a string
-(NSString *) componentsjoinedbystring: (NSString *) separator
Persisting Nsarray to a file
-(BOOL) WriteToFile: (NSString *) path atomically: (BOOL) Useauxiliaryfile

#pragma mark-nsarray traversal
    //Method One: Normal traversal (using for loop)
        void ArrayFor1 () {
        nsarray *array = [Nsarray arraywithobjects:@ 1 ", @" 2 ", @" 3 ", nil];
        int count = Array.count;
        for (int i=0; i<count; i++) {
               id obj = [array objectatindex:i];
             NSLog (@ "%i-%@", I, obj);
       }
      }

    /Method Two: Fast traversal
       void ArrayFor2 () {
            Nsarray *array = [Nsarray arraywithobjects:@ "1", @ "2", @ "3", nil];
           int count = Array.count;
           int i=0;
           for (id obj in array) {
                 NSLog (@ "%i-%@", I, obj);
                i++;
          }
        }

    //Method Three: Using block traversal
          void ArrayFor3 () {
               Nsarray * Array = [Nsarray arraywithobjects:@ "1", @ "2", @ "3", nil];
               [Array enumerateobjectsusingblock:^ (id obj, Nsuinteger idx, BOOL *stop) {
                        NSLog (@ "%zi->%@", IDX, obj);
                        //  *stop = YES; Change the outer bool, terminate the traversal
                  }];
            }

Method Four: Using the iterator
To introduce the-->nsenumerator iterator: The iterator of the collection, which can be used to traverse the collection elements, Nsarray have the appropriate method to get the iterator
Gets the iterator of a positive sequence traversal
-(Nsenumerator *) Objectenumerator;
Gets an iterator for reverse-sequence traversal
-(Nsenumerator *) Reverseobjectenumerator;
@ Common methods:
Get Next element
-(ID) nextobject;
Get all the Elements
-(Nsarray *) allobjects
void ArrayFor4 () {
Nsarray *array = [Nsarray arraywithobjects:@ "1", @ "2", @ "3", nil];
Nsenumerator *enumerator = [Array objectenumerator];//returns an iterator for an array
If you put it after the traversal, you get empty, because, after the traversal, there is no value.
Nsarray *array2 = [enumerator allobjects];
NSLog (@ "array2=%@", array2);

Gets the next element that needs to be traversed
ID obj = nil;
while (obj = [Enumerator nextobject]) {
NSLog (@ "obj=%@", obj);
}
}


Use block blocks to traverse the entire array. This block requires three parameters, and ID obj represents the elements in the array.
Nsuinteger idx The subscript of the element,
Boolbool *stop is an argument of type bool. The official description is as follows:
A reference to a Boolean value. The block can set the value to YES to stop further processing of the array.
The Stop argument is a out-only argument. You should only ever set this Boolean to YES within.
-(void) Enumerateobjectsusingblock: (void (^) (id obj, Nsuinteger idx,boolbool *stop) block
Call examples such as:

Copy Code code as follows:

Nsarray *array = [Nsarray arraywithobjects:@ "Wendy", @ "Andy", @ "Tom", @ "test", nil Nil];


[Array enumerateobjectsusingblock:^ (ID str,nsuinteger index, bool* te) {
NSLog (@ "%@,%d", Str,index);
}];

As with the above method, the difference is that a parameter is added here to indicate whether it is traversing backwards or forwards.
-(void) Enumerateobjectswithoptions: (nsenumerationoptions) opts Usingblock: (void (^) (id obj, nsuinteger idx,boolbool * Stop)) block
The invocation example is as follows:
Copy Code code as follows:

Nsarray *array = [Nsarray arraywithobjects:@ "Wendy", @ "Andy", @ "Tom", @ "test", nil Nil];


[Array enumerateobjectswithoptions:nsenumerationreverse usingblock:^ (ID str,nsuinteger index, bool* te) {
NSLog (@ "%@,%d", Str,index);
}];

Related Article

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.