How do you change the elements within an NSArray?

前端 未结 3 2000
一整个雨季
一整个雨季 2021-01-03 07:48

I am a bit confused as to how arrays are handled in Objective-C. If I have an array such as

NSarray *myArray = [[NSArray alloc]
                                     


        
3条回答
  •  旧时难觅i
    2021-01-03 08:14

    Write a helper method

    -(NSArray *)replaceObjectAtIndex:(int)index inArray:(NSArray *)array withObject:(id)object {
        NSMutableArray *mutableArray = [array mutableCopy];
        mutableArray[index] = object;
        return [NSArray arrayWithArray:mutableArray];
    }
    

    Now you can test this method with

    NSArray *arr = @[@"a", @"b", @"c"];
    arr = [self replaceObjectAtIndex:1 inArray:arr withObject:@"d"];
    logObject(arr);
    

    This outputs

    arr = (
        a,
        d,
        c
    )
    

    You can use similar method for NSDictionary

    -(NSDictionary *)replaceObjectWithKey:(id)key inDictionary:(NSDictionary *)dict withObject:(id)object {
        NSMutableDictionary *mutableDict = [dict mutableCopy];
        mutableDict[key] = object;
        return [NSDictionary dictionaryWithDictionary:mutableDict];
    }
    

    You can test it with

    NSDictionary *dict = @{@"name": @"Albert", @"salary": @3500};
    dict = [self replaceObjectWithKey:@"salary" inDictionary:dict withObject:@4400];
    logObject(dict);
    

    which outputs

    dict = {
        name = Albert;
        salary = 4400;
    }
    

    You could even add this as a category and have it easily available.

提交回复
热议问题