简体   繁体   中英

Test to Understand Objective-C Vs Pointers

I have wrote a test code to understand Objective C vs C pointers. Here is the code..

eg:

    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSMutableArray *sec_mut;
    if (array) {
        [array addObject:@"My"];
         [array addObject:@"name"];
         [array addObject:@"is"];
         [array addObject:@"BoB"];

            sec_mut = [[NSMutableArray alloc] init];

            if (sec_mut) {
                for (id obj in array) { // Is it allocating new object and adding or only points to already existing memory (just adding address)?
                    [sec_mut addObject:obj]; 
                }
            }
    }

    [array removeObjectAtIndex:0];

    for (id obj in sec_mut) {
        NSLog(@"str is %@\n",obj);
    }

Output: str is My str is name str is is str is BoB

Even though I've deleted object at index zero all 4 object are displaying properly in new array, so it is not only pointing and its having its own object, Am I right? or Is it a dangling pointer?

thanx

When inserting objects into Cocoa collections, objects are generally not copied, only retained. (I. e., yes, only the pointers are used to reference the objects.)

Imagine if you had two mail men who knew your address, if got rid of one of them, the other would still know where you live.

You're not actually deleting the object, just a reference to the object.

H2CO3是正确的,obj-c使用引用计数可以是一种智能内存管理方式。数组和sec_mut都保留对真实对象的引用,而不是复制的对象。您可以阅读有关引用计数技术的详细信息。

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