How do you change the elements within an NSArray?

前端 未结 3 1979
一整个雨季
一整个雨季 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条回答
  • 2021-01-03 08:14

    You need an NSMutableArray ..

    NSMutableArray *myArray = [[NSMutableArray alloc]
                                      initWithObjects:@"N", @"N", @"N", @"N", @"N",
                                      nil];
    

    and then

    [myArray replaceObjectAtIndex:0 withObject:@"Y"];
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 08:34

    You can't, because NSArray is immutable. But if you use NSMutableArray instead, then you can. See replaceObjectAtIndex:withObject::

    [myArray replaceObjectAtIndex:0 withObject:@"Y"]
    
    0 讨论(0)
提交回复
热议问题