OC NSArray练习题 和 NSSet的常用方法

时间:2021-04-10 00:10:46

#import <Foundation/Foundation.h>

#import "Book.h"


int main(int argc, const char * argv[]) {

    

    NSMutableArray *book = [NSMutableArray array];


    Book **mei = [[Book allocinitWithName:@"金瓶梅" withPrice:58];

    Book *xiyouji = [[Book allocinitWithName:@"西游记" withPrice:50];

    Book *sanguoyanyi = [[Book allocinitWithName:@"三国演义" withPrice:108];

  

    //添加书籍

    [book addObject:*mei];

    [book addObject:xiyouji];

    [book addObject:sanguoyanyi];

    //删除书籍

    [book removeObject:xiyouji];

    //查找书籍修改价格

    NSString *string1 = @"金瓶梅";

    for (Book *string in book) {

        if ([string.name isEqualToString:string1]) {

            string.price = 100;

            NSLog(@"%ld", string.price);

        }

    }

    //遍历书籍

    for (Book *string in book) {

        NSLog(@"%@", string.name);

    }

    //数值对象

    NSNumber *num = [NSNumber numberWithInteger:10];

    NSNumber *num1 = [NSNumber numberWithInt:12];

    //转换

    NSLog(@"%d", num1.intValue);

    NSLog(@"%ld", [num integerValue]);

    


Book.h

#import <Foundation/Foundation.h>


@interface Book : NSObject


@property(nonatomicretainNSString *name;

@property(nonatomicassignNSInteger price;



- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger )price;



@end



Book.m

#import "Book.h"


@implementation Book



- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger )price {

    self = [super init];

    if (self) {

        self.name = name;

        self.price = price;

    }

    return self;

}

@end


    


    //集合 (少用不能放重复的元素

    //创建集合对象 //集合是无序随机读取的所以不能按存储顺序取元素。

    NSSet *set1 = [[NSSet allocinitWithObjects:@"asd"@"bb"@"asdqw"@"wwwww"nil];

    NSSet *set = [NSSet setWithSet:set1];

    //获取元素个数

    //NSLog(@"%ld", set.count);

    //获取集合中得某一个元素

    NSLog(@"%@", [set anyObject]);

    //判断集合中是否存在某一对象 返回值BOOL类型

    if ([set containsObject:@"123"]) {

        NSLog(@"判断集合中是否存在某一个对象");

    } else {

        NSLog(@"不存在");

    }

    NSLog(@"%@", [set member:@"123"]);

    

    NSMutableSet *set2 = [NSMutableSet setWithSet:set];

    [set2 addObject:@"ccc"];//随机插入

    //删除对象

    [set2 removeObject:@"ccc"];

    NSLog(@"%@", set2);