Similarly, the array also has a variable form, that is, Nsmutablearray, and now we're going to implement these methods:
(1) New Person.h file, implemented as follows:
#import <Cocoa/Cocoa.h>
@interface person:nsobject
@property (nonatomic,strong) nsstring *personname;
-(Instancetype) Initwithpersonname: (NSString *) name;
@end
(2) New PERSON.M file, implemented as follows:
#import "Person.h"
@implementation person
//rewrite init method;
-(Instancetype) Initwithpersonname: (NSString *) name{
self = [super init];
if (self) {
_personname = name;
}
return self;
}
@end
(3) implemented as follows in MAIN.M:
#import <Foundation/Foundation.h> #import "Person.h" int main (int argc, const char * argv[]) {@autoreleasepool
{//add element; *person1 = [[Person alloc] initwithpersonname:@ ' Jack '];
Person *person2 = [[Person alloc] initwithpersonname:@ ' Mary '];
Person *person3 = [[Person alloc] initwithpersonname:@ "Robert"];
Nsmutablearray *arr = [[Nsmutablearray alloc] init];
[Arr Addobject:person1];
[Arr Addobject:person2];
[Arr Addobject:person3];
For (person *p in arr) {NSLog (@ "%@", p.personname);
Person *person4 = [[Person alloc] initwithpersonname:@ ' me '];
[Arr Addobject:person4];
For (person *p in arr) {NSLog (@ "%@", p.personname); //////////////////////////////////////////////////////////////////using another initialization method; Nsmutablearray *arr1 = [
[Nsmutablearray alloc] init];
Nsarray *ARR3 = [[Nsarray alloc] initwithobjects:person1,person2,person3, nil]; AttentionThe following method assigns each object in the array as an element to a mutable array; [arr1 ADDOBJECTSFROMARRAY:ARR3];
Note that the following method assigns the entire array as an object to the variable array;//[arr1 ADDOBJECT:ARR3];
NSLog (@ "%@", arr1);
Delete elements;//delete all elements within the array;//[arr1 removeallobjects];
Delete the last element;//[arr1 removelastobject];
The position of the exchange element; [arr1 exchangeobjectatindex:0 withobjectatindex:1];
NSLog (@ "%@", arr1);
return 0; }
The output results are as follows:
。
GitHub home: https://github.com/chenyufeng1991. You are welcome to visit.