NSMutableArray vs NSArray which is better

后端 未结 6 1664
再見小時候
再見小時候 2021-02-05 18:11

This is a bit of a silly question, but if I want to add an object to an array I can do it with both NSMutableArray and NSArray, which should I use?

6条回答
  •  耶瑟儿~
    2021-02-05 18:31

    When deciding which is best to use:

    NSMutableArray is primarily used for when you are building collections and you want to modify them. Think of it as dynamic.

    NSArray is used for read only inform and either:

    • used to populate an NSMutableArray, to perform modifications
    • used to temporarily store data that is not meant to be edited

    What you are actually doing here:

    NSArray * array2;
    array2 = [array2 arrayByAddingObject:obj];
    

    is you are creating a new NSArray and changing the pointer to the location of the new array you created.

    You are leaking memory this way, because it is not cleaning up the old Array before you add a new object.

    if you still want to do this you will need to clean up like the following:

    NSArray *oldArray;
    NSArray *newArray;
    newArray = [oldArray arrayByAddingObject:obj];
    [oldArray release];
    

    But the best practice is to do the following:

    NSMutableArray *mutableArray;
    // Initialisation etc
    [mutableArray addObject:obj];
    

提交回复
热议问题