Objective-C Foundation架構實踐——NSMutableArray(一)__nsmutablearray

來源:互聯網
上載者:User

     同樣的,數組也有可變的形式,即NSMutableArray,現在我們來實現這些方法:

(1)建立Person.h檔案,實現如下:

#import <Cocoa/Cocoa.h>@interface Person : NSObject@property(nonatomic,strong) NSString *personName;- (instancetype)initWithPersonName: (NSString *)name;@end

(2)建立Person.m檔案,實現如下:

#import "Person.h"@implementation Person//重寫init方法;- (instancetype)initWithPersonName: (NSString *)name{    self = [super init];  if (self) {    _personName = name;  }    return self;}@end

(3)在main.m中實現如下:

#import <Foundation/Foundation.h>#import "Person.h"int main(int argc, const char * argv[]) {  @autoreleasepool {            //添加元素;    Person *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);    }        ////////////////////////////////////////////////////////////////    //使用另一種初始化方式;    NSMutableArray *arr1 = [[NSMutableArray alloc] init];    NSArray *arr3 = [[NSArray alloc] initWithObjects:person1,person2,person3, nil];    //注意下面的方法是把數組中的每一個對象作為元素來賦值給可變數組;    [arr1 addObjectsFromArray:arr3];        //注意下面的方法是把整個數組作為一個對象然後來賦值給可變數組;    //    [arr1 addObject:arr3];    NSLog(@"%@",arr1);            //刪除元素;    //刪除數組內所有元素;    //    [arr1 removeAllObjects];        //刪除最後一個元素;    //    [arr1 removeLastObject];            //交換元素的位置;    [arr1 exchangeObjectAtIndex:0 withObjectAtIndex:1];    NSLog(@"%@",arr1);          }  return 0;}

輸出結果如下:



github首頁:https://github.com/chenyufeng1991  。歡迎大家訪問。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.