Weak object in an NSDictionary?

前端 未结 3 786
無奈伤痛
無奈伤痛 2020-12-28 16:23

I would like to store a zeroing weak reference to an object in a NSDictionary. This is for a reference to a parent NSDictionary, so I can crawl bac

3条回答
  •  有刺的猬
    2020-12-28 16:37

    There is a built-in way; just use:

    [array addObject:[NSValue valueWithNonretainedObject:object]];
    

    Then to access the object later, use:

    id object = [[array objectAtIndex:i] nonretainedObjectValue];
    

    If the value has been released since you added it then "object" will be an invalid pointer under iOS 4.x, and (I'm assuming) will be nil under 5.x with ARC enabled.

    EDIT: my assumption was wrong - it's not weak under ARC (see discussion below).

提交回复
热议问题