Namhcir
Namhcir

Reputation: 815

How do you change the elements within an NSArray?

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]
                                  initWithObjects:@"N", @"N", @"N", @"N", @"N",
                                  nil];

how do I change the first occurrence to "Y"?

Upvotes: 4

Views: 14015

Answers (3)

Bob Ueland
Bob Ueland

Reputation: 1834

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.

Upvotes: 4

Adam Batkin
Adam Batkin

Reputation: 53034

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

[myArray replaceObjectAtIndex:0 withObject:@"Y"]

Upvotes: 5

Kal
Kal

Reputation: 24910

You need an NSMutableArray ..

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

and then

[myArray replaceObjectAtIndex:0 withObject:@"Y"];

Upvotes: 9

Related Questions