简体   繁体   中英

Adding a instance of `NSMutableArray` into `NSArray` objects

I am adding a instance of NSMutableArray in NSArray .

Code:

    NSMutableArray *var2=[[NSMutableArray alloc]init];
    [var2 addObject:@"c++"];
    NSArray *var1=[[NSArray alloc]initWithObjects:var2, nil];
    [var2 addObject:@"c"];
    [var2 addObject:@"wt"];
    NSLog(@"Mutable%@",var2);
    NSLog(@"Simple%@",var1);

Output:

2015-07-29 14:51:10.494 Kom4[3249:60b] Mutable(
    "c++",
    c,
    wt
)
2015-07-29 14:51:10.496 Kom4[3249:60b] Simple(
        (
        "c++",
        c,
        wt
    )
)

Question: NSArray size will be fixed at the time of initialisation. But we are passing instance of NSMutableArray .It is of flexible size. How is this showing the output?

No, the NSArray will remain fixed (it's immutable) and isn't flexible at.

This is because you are holding a reference to the object and a reference never changes in size, regardless of how large the referenced object gets.

you have initialized your NSArray with an object, so the array holds a pointer to that object.

If you want to initialize it with the mutable array's objects, use "initWithArray:" instead: https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html

Your output just shows the same: An Array, which has exactly one object: another array with 3 Elements:

In Short:

@[
    @[
         @"c++",
         @"c",
         @"wt",
     ]
]

Your NSArray is fixed. It contains your NSMutableArray and nothing else; that NSMutableArray cannot be removed, nothing else can be added to the NSArray, so it will contain the NSMutableArray and nothing else until the end of its lifetime.

That doesn't mean you cannot change the NSMutableArray. It's always the same array, but with different contents. That's what your NSLog shows; the NSArray contains the same object, but with different contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM