How do I convert NSMutableArray to NSArray?

前端 未结 9 794
清酒与你
清酒与你 2020-12-04 04:38

How do I convert NSMutableArray to NSArray in objective-c?

9条回答
  •  执笔经年
    2020-12-04 05:13

    An NSMutableArray is a subclass of NSArray so you won't always need to convert but if you want to make sure that the array can't be modified you can create a NSArray either of these ways depending on whether you want it autoreleased or not:

    /* Not autoreleased */
    NSArray *array = [[NSArray alloc] initWithArray:mutableArray];
    
    /* Autoreleased array */
    NSArray *array = [NSArray arrayWithArray:mutableArray];
    

    EDIT: The solution provided by Georg Schölly is a better way of doing it and a lot cleaner, especially now that we have ARC and don't even have to call autorelease.

提交回复
热议问题