How do you change the elements within an NSArray?

南楼画角 提交于 2019-11-30 15:52:12

问题


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"?


回答1:


You need an NSMutableArray ..

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

and then

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



回答2:


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

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



回答3:


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.



来源:https://stackoverflow.com/questions/6685819/how-do-you-change-the-elements-within-an-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!